We know the need for a virtual destructor.
Base *bptr = new Derived();
delete bptr;
If a derived class object is pointed by a base class pointer and when the object goes out of scope, only the Base class destructor gets called unless the destructor is virtual.
I am wondering how does the constructor work properly in this case.
Since the Base pointer points to the Derived object, only the Base constructor should have got called. How is it calling the derived class constructor properly.
Please explain me the reason behind this.
While creating the object with
newwe have the complete information of the object;LHS part where you assign pointer is irrelevant. That’s why you don’t need such
virtualmechanism for constructor. See Bjarne Stroustrup‘s page for more info.Other note,
virtualdestructor is needed, because you are using pointer todeletethe object.