user13707437
user13707437

Reputation:

inheriting default constructor, a contradiction?

In C++ (inheritance subject) I read:

A derived class automatically has a default constructor, a copy constructor, and an assignment operator, like any other class. The compiler-generated default constructor calls the base class default constructor

But on the other hand:

The base class constructors are not inherited We must explicitly define any constructors the derived class needs

1) what does it mean to inherit a constructor?

2) isn't what is written above a contradiction?

I hope to add some examples if possible to help me understand.

Upvotes: 0

Views: 77

Answers (2)

Pete Becker
Pete Becker

Reputation: 76245

struct s {
    s() : s_str("my string") {}; // default constructor
    std::string s_str;
};

struct d : s {
    std::string d_str;
};

If d didn't have any members that needed construction, the default constructor would simply construct s with s::s() which superficially looks like inheritance (and could be implemented that way). But when you add data members to the derived class, that won't work.

The default constructor for s constructs s_str with the text "my string".

If s::s() was inherited in d it wouldn't know about d_str, so wouldn't construct it. So it's not inherited.

Instead, the compiler generates a default constructor for d that constructs d_str with the default constructor for std::string and constructs the s base with s::s().

Upvotes: 0

Stephan Lechner
Stephan Lechner

Reputation: 35154

"The base class constructors are not inherited" means that any constructor defined in a class Base is not available for a derived class Derived unless it is re-defined in Derived. This is also valid for the default constructor. But, "A derived class automatically has a default constructor" says that the compiler will automatically generate a default constructor, just as it does for every class. So the compiler will re-define a default constructor in a derived class; it is still not inherited.

The only thing is that "We must explicitly define any constructors the derived class needs", if there is no context under which this statement shall hold, seems wrong. There are definitely constructors available in a derived class that have not been defined explicitely. This can be shown easily by defining a derived class without any explicit constructor:

struct Base {
    Base () { std::cout << "in default constructor of Base; not inherited, but still called." << std::endl; };
};

struct Derived : public Base {
   // no explicitly defined constructor...
};

int main() {
    Derived d;
}

Output:

in default constructor of Base; not inherited, but still called.

So I'd tend to say that the statement "... We must explicitly define any constructors the derived class needs" you cited is either not precise, not shown in full context, or wrong.

Upvotes: 2

Related Questions