简体   繁体   中英

how to specify constructor in header for child and parent class

I am new to C++ and define a parent class in a header file parent.h . It has a constructor Parent(int a, int b) .

Now I want to write the header file for the child class child.h , which inherits the exact same constructor as the parent class and only has additional member functions.

Do I have to specify the constructor in the child's header file as well? ( Child(int a, int b) ) Or do I only specify the signatures for the additional member functions and specify the constructor in the corresponding child.cpp file?

Constructors aren't inherited. Therefore, if you want your child class to have the specified constructor you will need to provide it explicitly inside your class definition:

…
Child(int a, int b) : Parent(a, b) {}
…

Or pull in the definition from the parent class:

using Parent::Parent;

Note that this will pull in all constructor overloads. This may not be what you intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM