I ran into a very nasty error today, here is a MWE:
#include <iostream>
class X {
public:
X() { std::cout << "Default" << std::endl; }
X(int a) { std::cout << a << std::endl; }
};
class Y : public X { };
class Z : public Y {
using X::X;
};
int main() {
Z instance{3};
}
Contrary to my expectations, "Default
" gets printed. Admittedly, the code is faulty because the inherited constructors of Z
try to initialize X
without specifying how to construct Y
(∗). But still, shouldn't the compiler complain? What's the rationale behind the default constructor of Y
(and subsequently X
) getting called, completely silently ignoring my parameter of 3
? Is this documented somewhere in the standard? Or is it a bug in my compiler?
My environment is gcc version 6.2.1 20160916 (Red Hat 6.2.1-2)
. No compiler warning is produced even with -Weffc++ -Wall -Wextra -pedantic
.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.
It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.
It's a g++ bug, the code is invalid. Only constructors from direct bases can be inherited:
[namespace.udecl] §3 If such a using-declaration names a constructor, the nested-name-specifier shall name a direct base class of the class being defined
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