简体   繁体   中英

Constructor behaviour in runtime polymorphism

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.

new Derived() has no base class reference anywhere. You may choose to even assign it to nothing. Hence what the resulting pointer gets assigned to doesn't affect the construction.

When you execute the following:

Base *bptr = new Derived();

you are invoking the new operator for the Derived class, because that's what you are constructing.

When you assign the Derived* returned by new to a Base* , you are simply up-casting the pointer which is an implicit operation.

While creating the object with new we have the complete information of the object;

new Derived(); // static type is same as dynamic type

LHS part where you assign pointer is irrelevant. That's why you don't need such virtual mechanism for constructor. See Bjarne Stroustrup 's page for more info.

Other note, virtual destructor is needed, because you are using pointer to delete the object.

delete bptr; // static type may not be same as dynamic type

You explicitly say that you want to construct an instance of Derived :

Base *bptr = new Derived();

means please construct an object if type class Derived and then please store a pointer to that object in bptr . So the compiler has nothing to guess or deduce .

Compare it with:

new Derived();

that creates an object of class Derived and leaks that object. The compiler has nothing to guess or deduce here either. The only difference between these two snippets is that the former stores the pointer and the latter doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM