Question

I am having trouble understanding virtual functions. When I overload a virtual function, is the new derived function called only? Or both derived and base functions? Because I noticed that when virtual destructors are called, the base AND the derived class destructors are called.

Was it helpful?

Solution

destructors are special member functions in this particular regards.
If you have a virtual base class destructor then it will properly call Base as well as derived class destructors during polymorphic deletion(calling delete on base class pointer pointinf to derived class object.).

However, Other virtual member functions do not share the same special status as destructors. Only the function defined for the appropriate object type gets called. If you need any other function to be called you need to do so explicitly.

OTHER TIPS

a derived class object is nothing but a kind of wrapper to the base class object. So in case of destructors,both the destructors should be called which is an expected behaviour.

In case of virtual function, you are given a chance to replace the function in a base class.so using a base class pointer to hold a derived class object will only call the virtual function in the derived class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top