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 cla开发者_Python百科ss constructor properly.
Please explain me the reason behind this.
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
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.
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.
精彩评论