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