Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 970
user3658679 Avatar asked Jun 04 '14 20:06

user3658679


People also ask

How do you call the base class constructor in inheritance?

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++

Does base class constructor get called automatically?

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.

Do you put constructors in header files?

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.

Which is the correct way to call base class constructor in C#?

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.


2 Answers

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
}
like image 174
wolfPack88 Avatar answered Oct 29 '22 07:10

wolfPack88


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) {
}
like image 28
πάντα ῥεῖ Avatar answered Oct 29 '22 08:10

πάντα ῥεῖ