Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Base constructor delegating/forwarding to derived class with "using" keyword

struct B {
  B () {}
  B(int i) {}
};

struct D : B {
  using B::B;  // <--- new C++11 feature
};

D d1; // ok
D d2(3); // ok

Now, if I add a new constructor inside the body of struct D, such as:

struct D : B {
  using B::B;
  D(const char* pc) {}  // <--- added
};

then D d1; starts giving compiler error(ideone is not upgraded yet, I am using g++ 4.8.0)? However D d2(3); still works.

Why the default constructor is discounted when adding a new constructor inside struct D?

like image 849
iammilind Avatar asked May 08 '13 17:05

iammilind


People also ask

What is constructor delegation?

Delegating constructors can call the target constructor to do the initialization. A delegating constructor can also be used as the target constructor of one or more delegating constructors. You can use this feature to make programs more readable and maintainable.

How do you call a base class constructor from a derived class in C++?

How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++

Can we use constructor in derived class?

Constructors in Derived Class in C++If the class “A” is written before class “B” then the constructor of class “A” will be executed first. But if the class “B” is written before class “A” then the constructor of class “B” will be executed first.

Can constructors be defined overridden in derived class?

Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass.


1 Answers

There is a subtle difference between

struct D : B {
 using B::B;
 D(const char* pc) {}  // <--- added
};

versus

struct D : B {
 using B::B;
};

In the second case, compiler auto-generate the default "D(){}" constructor for you. But if you create your own constructor for D, then the default "D(){}" is not available anymore. Sure you have inherited B's default constructor, but that doesn't tell the compiler how to construct D by default.

like image 151
dchhetri Avatar answered Sep 24 '22 10:09

dchhetri