Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't C++ constructors inherited?

Why is the Child pass-through constructor necessary in this code? I would think that it wouldn't be, but the compiler (gcc and VS2010) complains when I remove it. Is there an elegant workaround? It just seems pointless to have to insert this shim into child classes.

class Parent
{
public:
  Parent(int i) { }
};

class Child : public Parent
{
public:
  Child(int i) : Parent(i) { }
};

int main()
{
  Child child(4);
  return 0;
}
like image 645
plong Avatar asked Jul 15 '11 16:07

plong


2 Answers

Because the following is perfectly valid:

class Parent
{
public:
    Parent(int i) { }
};

class Child : public Parent
{
public:
    Child() : Parent(42) { }
};

How is the compiler to guess whether you want the derived child to have a forwarded constructor? And in the case of multiple inheritance, the set of constructors from the two types may not match; when forwarding a constructor from base class A, which constructor on base class B should be called?

Technically, I suppose the language designers could have said that if the type has a single base class and in the absence of an explicit constructor, all parent constructors are forwarded. However, that creates the opposite problem: if a base class has multiple constructors including a default constructor, and the child wishes to allow only the default constructor, this must now be explicitly specified.

like image 52
Sven Avatar answered Oct 23 '22 02:10

Sven


If you don't specify which parent constructor should be called explicitly, the compiler will generate code which calls the default (no-argument or with all default values) constructor.

In your case, the class Parent does not have such a constructor, the compiler would not know what value to use for i.

Not specifying a constructor in class Child means that the default constructor in class Parent would be called but this does not exist.


I haven't tried it but have a look at this section of the C++0x FAQ. I have the impression what you're asking for is possible in C++0x.

like image 26
Andre Holzner Avatar answered Oct 23 '22 03:10

Andre Holzner