Caution with C ++ 11 Inherited Constructor

https://en.wikipedia.org/wiki/C++11#Object_construction_improvement

For base class constructors, C ++ 11 allows the class to specify this base class constructors will be inherited. Thus, the C ++ 11 compiler generate code to perform inheritance and forward the derived class to the base class. This is an all-or-nothing function: either all base class constructors are forwarded, or none of them. In addition, there are restrictions for multiple inheritance, so class constructors cannot be inherited from two classes that use constructors with the same signature. Also, there cannot be a constructor in a derived class exists that matches the signature in the inherited base class.

Can someone give me an example to illustrate the problem with " . There cannot exist a constructor in a derived class that matches the signature in an inherited base class. "?

+4
source share
1 answer

This means that if you have a constructor in a derived class whose parameter list matches the parameter list of any constructor in the base class, then this constructor of the derived class is taken and hides the base class'

eg.

struct Foo
{
   Foo(){std::cout << "Foo default ctor\n";}
   Foo(int){std::cout << "Foo(int)\n";}
};

struct Bar : Foo
{
   using Foo::Foo;
   Bar(int){std::cout << "Bar\n";} // won't implicitly call Foo(int)
};

int main()
{
    Bar b(1);
}

From Β§12.9 / 3 [class.inhctor] (Emphasis mine):

, copy/move, , , , , , , .

+6

Source: https://habr.com/ru/post/1672281/


All Articles