开发者

What is default destructor if a class inherits from a pure base class?

开发者 https://www.devze.com 2023-02-27 04:45 出处:网络
Considering next two classes : struct Base { virtual ~Base() { } virtual void foo() = 0; }; struct Derived : public Base

Considering next two classes :

struct Base
{
  virtual ~Base()
  {
  }

  virtual void foo() = 0;
};

struct Derived : public Base
{
  virtual void foo()
  {
  }
};

Is the following causing an undefined behaviour :

Base *obj = new Derived;开发者_如何学C
delete obj;

?

Additional question : how come that one a method is declared virtual, it is virtual in derived classes (even if the virtual keyword is not used in the derived class), but it is not true for destructors?


Is the following causing an undefined behaviour :

No, that is not invoking undefined behaviour precisely because the destructor of Base is virtual.


EDIT: Its just to clarify a doubt (raised in the following comment), and to emphasize what I said above.

@Oli Charlesworth commented:

Technically, even if it were not declared virtual, the behaviour would not be undefined, it would just be undesirable.

No. The behavior would be undefined.

The section §5.3.5/3 from the Standard says,

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

I think it helps removing the doubt.:-)


That is not undefined behaviour. You've declared the base-class destructor as virtual, so at runtime, delete obj will first invoke the "default" destructor in Derived (as you haven't explicitly declared one), and then the destructor in Base.


Since you have declared the base class's destructor as virtual, there is no undefined behavior here.

The statments :

Base *obj = new Derived;
delete obj;

will lead to call the derived class's desctructor and then the Base class's destructor. I didn't get the second question though


For any class, constructors and destructors aren't inherited. This is specified in the standard. As such, your code won't cause undefined behaviour, as it will invoke the default constructor/destructor for the class.
It is for this reason that inheritence doesn't hold true for destructors/constructors. It doesn't make sense for a constructor/destructor to be inherited from a parent object, as this object could potentially have all forms of different members.

0

精彩评论

暂无评论...
验证码 换一张
取 消