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?
To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++
If a base class has a default constructor, i.e., a constructor with no arguments, then that constructor is automatically called when a derived class is instantiated if the derived class has its own default constructor.
You should generally put declarations in the header and implementation in the code file. The declaration of the copy constructor, and all other member functions, should be inside the class declaration in the . h header file.
Calling base class constructor in C# In c#, the base keyword is used to access the base class constructor as shown below. In the below code we declare a constructor in a derived class. We have used the ':base(...)' keyword after the constructor declaration with a specific parameter list.
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With