order of destruction using virtual

前端 未结 8 1278
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 00:35

Can some one please help what the order of destruction is when I am using virtual functions. Does it start with the base class and then derived class?

8条回答
  •  青春惊慌失措
    2021-02-06 01:25

    First the derived, then the base. No difference wrt the non-virtual cases.

    Additional note. When you have inheritance and virtual methods, you have to declare destructors as virtual, otherwise you can have undefined behavior at deletion.

    Example, suppose Derived is derived from Base, and you allocate Derived with the following line:

    Base *o = new Derived();
    delete(o);
    

    If this case occurs in your code, and Base has no virtual destructor, the resulting behavior is undefined. Typically, only the destructor of Base will be called. The destructor of Derived will not be called, because you are calling delete on a Base pointer. However, the program might crash instead. Once you are in the realm of undefined behavior, all bets are off and your running code is doomed. To prevent chaos the Base destructor must be virtual.

提交回复
热议问题