Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About constructor call for base and derived class

Tags:

c++

oop

I am new in C++ and I have just started studying polymorphism. I know that if I create an object for the derived class then the constructor of both derived and base class is get called. Does it mean that, when I create an object for the derived class, eventually I am ending up with two objects- one is created by the constructor of base class and another one created by the constructor of derived class?

Can anyone explain, what is the job of base class constructor when I want to create an object for the derived class.

like image 294
newbie Avatar asked Dec 10 '22 03:12

newbie


2 Answers

The job of the base class constructor is to initialise the base class member variables (consider the case of a private member variable in the base class).

When you call a constructor for a derived object, you only end up with one object. The base class constructor initialises the base class parts of the new object, and the derived constructor initialises the derived class parts of the same new object.

like image 89
Greg Hewgill Avatar answered Dec 26 '22 08:12

Greg Hewgill


Constructors do not allocate space and initiate instances of objects; they initialise the object immediately after space has been allocated.

When you declare a object on the stack or use new first the memory is reserved and object is created, then the constructors are executed, starting with the base constructor and working upwards towards the most derived class.

like image 30
Elemental Avatar answered Dec 26 '22 10:12

Elemental