简体   繁体   中英

C++ Inheritance: Calling Base Class Constructor In Header

Assume class Child is a derived class of the class Parent . In a five file program, how would I specify in Child.h that I want to call the constructor of Parent ? I don't think something like the following is legal inside the header:

Child(int Param, int ParamTwo) : Parent(Param);

In this situation, what should Child.cpp 's constructor syntax look like?

In Child.h, you would simply declare:

Child(int Param, int ParamTwo);

In Child.cpp, you would then have:

Child::Child(int Param, int ParamTwo) : Parent(Param) {
    //rest of constructor here
}

The initialization list of a constructor is part of its definition. You can either define it inline in your class declaration

class Child : public Parent {
    // ...
    Child(int Param, int ParamTwo) : Parent(Param)
    { /* Note the body */ }
};

or just declare it

class Child : public Parent {
    // ...
    Child(int Param, int ParamTwo);
};

and define in the compilation unit ( Child.cpp )

Child::Child(int Param, int ParamTwo) : Parent(Param) {
}

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