简体   繁体   中英

Detructors and inherited functions c++

if i have two classes like this:

class A
{
   public:
   virtual print(){};
   ~A(){print();}
};
class B:public A
{
   public:
   print(){};
   ~B(){}
};
void main()
{
  B *b1=new B;
  delete b1;
}

in the destructor in class A does it call print from class A and not from B because when it is in class A destructor,class B is technically destructed?

Yes, thats right. A class is destructed by calling the destructor for itself, and then the destructor for its parent classes, which means by the time you destruct A, B is already gone. You will see similar behaviour if you invoke virtual, overriden functions in your base classes when constructing.

It is generally considered bad practice to call virtual functions in constructors or destructors, as the behaviour, while well-defined, can be misleading to the uninitiated. It's also easy to trip yourself up even if you are initiated.

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