Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting second-level base class constructor: silent error

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.

like image 510
The Vee Avatar asked Sep 26 '16 12:09

The Vee


People also ask

Is it possible to inherit the constructors of its base class?

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.

Is it possible to inherit constructors of its base class in C++?

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.

How do you override a base class constructor?

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.

Can a derived class have 2 base classes?

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.


1 Answers

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

like image 143
n. 1.8e9-where's-my-share m. Avatar answered Oct 07 '22 11:10

n. 1.8e9-where's-my-share m.