virtual function | Sololearn: Learn to code for FREE!

0

virtual function

class super { public: virtual~super(){cout<<1;} }; class sub: public super { public: ~sub(){cout << 2;} }; int main(){ super*ptr = new sub delete ptr; } // outputs 21 Why does the 1 get outputted? I believe that the pointer points to the sub class's sub function, which prints out 2. But I don't understand what allows the base class's super function to be expressed... Is there something I should know about virtual functions?

7/24/2020 8:14:19 AM

Solus

1 Answer

New Answer

0

Order of destruction is reverse of order of construction. ptr is a pointer of type super but holding a pointer to the sub object. Then you delete the object through super class pointer. Since the destructor is virtual it will go all the way down to the last dervied class first, then work it out to top (base class) If the destructor is not virtual then only super destructor will be called, thus leaking resources if the pointer was actually pointing to the derived class object. This also applies to the "references"