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
?
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 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++
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With