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.
No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
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.
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.
Destructor of base class should always be virtual.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With