I use Borland C++ Builder.
And i had o problem
#include <Classes.hpp>
class TMyObject : public TObject
{
__fastcall TMyObject();
__fastcall ~TMyObject();//I would like to inherite my destructor from TObject
};
__fastcall TMyObject::TMyObject() : TObject()//it will inherited my constructor from TObject
{
}
And for that new destructor that will inherite ~TObject
?
__fastcall TMyObject::~TMyObject?????????????
Destructors are not inherited. If a class doesn't define one, the compiler generates one. For trivial cases that destructor just calls the base class' destructor, and often that means that there is no explicit code for its destructor (which imitates inheritance).
Destructors and InheritanceBecause the base class destructor is inherited, and because the derived class object "is" a base class object, both the derived class destructor (even if it is the "default" destructor) and the base class destructor are called automatically.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
Inheritance is one of the key features of Object-oriented programming in C++. It allows us to create a new class (derived class) from an existing class (base class). The derived class inherits the features from the base class and can have additional features of its own.
This can be solved at TObject
's level. Its destructor has to be virtual:
#include <Classes.hpp>
class TObject
{
__fastcall TObject();
virtual __fastcall ~TObject();
};
This way you can either do:
TObject * pobj = new TMyObject();
delete pobj;
or
TMyObject * pobj = new TMyObject();
delete pobj;
Both destructors will be called (~TMyObject()
first and then ~TObject()
) and you will have no leak.
Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly.
TMyObject::TMyObject() : TObject()
Does not inherit the constructor.
It is called as Member initializer list and it initializes the Base class object with a particular value.
When you create the object.
TMyObject obj;
The constructors will be called in order:
constructor of TObject
constructor of TMyObject
When the object life time ends the destructors will be called in the order:
destructor of TMyObject
destructr of TObject
The compiler will do so for you, do not need to call it explicitly.
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