Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to explicitly call base class destructor/constructor?

Is it legal to destruct and construct a base class object in place to reset the portion of the state known to the base class?

class C : public BaseClass {...};

C c;
c.BaseClass::~BaseClass();
new (static_cast<BaseClass*>(&c)) BaseClass;

Clearly there are other ways to achieve this effect if we have access to the source code of the classes. However, I want to know from a language perspective if there is a specific reason why this is invalid.

like image 532
Brice M. Dempsey Avatar asked Aug 29 '14 11:08

Brice M. Dempsey


People also ask

Does base class destructor get called?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

Can we declare base class constructor or destructor as virtual?

Virtual Constructor in C++ In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual. But virtual destructor is possible.

Can I inherit the constructor and destructor of a base class?

Inheritance in Parametrized Constructor/ DestructorDerived class doesn't inherit constructors and destructors of the base class. It only inherits all the members(fields, methods) of the base class. This is because constructors are not members of the class, they are just use initialize the object values.

Which of the following statement is correct regarding destructor of base class?

Destructor of base class should always be virtual.


1 Answers

No, this is not legal. You're not allowed to replace the base subobject of an object.

C++11 3.8/7 specifies that you can only reuse an object's storage if

the original object was a most derived object (1.8) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

The object you replace was a base class subobject, not a most derived object, and so is forbidden.

If you were to replace the entire object (i.e. call ~C, then construct a new C), then that would be legal, but dangerous. If the constructor threw, then the object would be destroyed a second time at the end of its lifetime. That would give undefined behaviour.

like image 107
Mike Seymour Avatar answered Oct 17 '22 15:10

Mike Seymour