Tuesday, January 15, 2019

c++ - Inheriting constructors




Why does this code:



class A
{
public:
explicit A(int x) {}
};

class B: public A

{
};

int main(void)
{
B *b = new B(5);
delete b;
}



Result in these errors:




main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B()
main.cpp:8: note: B::B(const B&)


Shouldn't B inherit A's constructor?




(this is using gcc)


Answer



If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:



class A
{
public:
explicit A(int x) {}
};


class B: public A
{
using A::A;
};


This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.



Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...