C++ Inheritance: Calling Base Class Constructor In Header
12,783
Solution 1
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
}
Solution 2
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) {
}
Author by
user3658679
Updated on June 03, 2022Comments
-
user3658679 about 2 years
Assume class
Child
is a derived class of the classParent
. In a five file program, how would I specify inChild.h
that I want to call the constructor ofParent
? 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? -
Wolf about 10 years+1 BTW: using
implementation
instead ofdefinition
could be less misleading. -
Vinz over 8 yearsWhat if I don't have a .cpp file and it's something like an interface?