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?????????????
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 destroy a TMyObject through a reference of type TMyObject you don't have to do anything. In case you have a pointer/reference of type TObject to a TMyObject things will go wrong. Only the TObject destructor will be called, not the TMyObject one:
TObject* p = new TMyObject;
delete p; // Only the TObject::~TObject is called, not TMyObject::~TMyObject.
To have the decision on what destructor to call deferred to runtime, you need to specify the destructor as virtual in TObject. Whenever you have a class that is intended to be derived from, the destructor should be virtual. Otherwise there is always a risk for resource leaks when the derived class destructor isn't called properly.
What's causing the confusion to you is that you can specifically mention "which" constructor of the base class you want to use as in the following example. But you can't/ don't need to specify the destructor.
TMyObject::TMyObject() : TObject()
You could use a different constructor, say TObject (int i) by writing
TMyObject::TMyObject() : TObject (3)
An object can be destructed in only one way but it can be constructed in several ways (by having different constructors).
So, in short, you don't need to mention the name of the base class destructor in the derived class destructor. As soon as you destroy the derived object (say, by doing delete derivedObj), it will first call the derived class destructor and then base class destructor by itself.
Related
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.
For example
class Interface
{
virtual void doSomething() = 0;
};
class Derived : public Interface
{
Derived();
~Derived()
{
// Do some important cleanup...
}
};
void myFunc(void)
{
Interface* p = new Derived();
// The behaviour of the next line is undefined. It probably
// calls Interface::~Interface, not Derived::~Derived
delete p;
}
The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor.
You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor.
You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases.
[See item 4 in this article: http://www.gotw.ca/publications/mill18.htm]
I decided to do some research and try to summarise your answers. The following questions will help you to decide what kind of destructor you need:
Is your class intended to be used as a base class?
No: Declare public non-virtual destructor to avoid v-pointer on each object of the class *.
Yes: Read next question.
Is your base class abstract? (i.e. any virtual pure methods?)
No: Try to make your base class abstract by redesigning your class hierarchy
Yes: Read next question.
Do you want to allow polymorphic deletion through a base pointer?
No: Declare protected virtual destructor to prevent the unwanted usage.
Yes: Declare public virtual destructor (no overhead in this case).
I hope this helps.
* It is important to note that there is no way in C++ to mark a class as final (i.e. non subclassable), so in the case that you decide to declare your destructor non-virtual and public, remember to explicitly warn your fellow programmers against deriving from your class.
References:
"S. Meyers. More Effective C++, Item 33 Addison-Wesley, 1996."
Herb Sutter, Virtuality, 2001
C++ Faq, 20.7, "When should my destructor be virtual?"
The answers to this question, of course.
Yes it is always important. Derived classes may allocate memory or hold reference to other resources that will need to be cleaned up when the object is destroyed. If you do not give your interfaces/abstract classes virtual destructors, then every time you delete a derived class instance via a base class handle your derived class' destructor will not be called.
Hence, you're opening up the potential for memory leaks
class IFoo
{
public:
virtual void DoFoo() = 0;
};
class Bar : public IFoo
{
char* dooby = NULL;
public:
virtual void DoFoo() { dooby = new char[10]; }
void ~Bar() { delete [] dooby; }
};
IFoo* baz = new Bar();
baz->DoFoo();
delete baz; // memory leak - dooby isn't deleted
It is not always required, but I find it to be good practice. What it does, is it allows a derived object to be safely deleted through a pointer of a base type.
So for example:
Base *p = new Derived;
// use p as you see fit
delete p;
is ill-formed if Base doesn't have a virtual destructor, because it will attempt to delete the object as if it were a Base *.
It's not only good practice. It is rule #1 for any class hierarchy.
The base most class of a hierarchy in C++ must have a virtual destructor
Now for the Why. Take the typical animal hierarchy. Virtual destructors go through virtual dispatch just as any other method call. Take the following example.
Animal* pAnimal = GetAnimal();
delete pAnimal;
Assume that Animal is an abstract class. The only way that C++ knows the proper destructor to call is via virtual method dispatch. If the destructor is not virtual then it will simply call Animal's destructor and not destroy any objects in derived classes.
The reason for making the destructor virtual in the base class is that it simply removes the choice from derived classes. Their destructor becomes virtual by default.
The answer is simple, you need it to be virtual otherwise the base class would not be a complete polymorphic class.
Base *ptr = new Derived();
delete ptr; // Here the call order of destructors: first Derived then Base.
You would prefer the above deletion, but if the base class's destructor is not virtual, only the base class's destructor will be called and all data in derived class will remain undeleted.
Given the following example:
class BaseClass
{
BaseClass()
{
};
virtual ~BaseClass()
{
this->Cleanup();
};
virtual void Cleanup()
{
// Do cleanup here.
};
};
class Level1DerivedClass : public BaseClass
{
Level1DerivedClass()
{
};
virtual ~Level1DerivedClass()
{
};
virtual void Cleanup()
{
// Call my base cleanup.
BaseClass::Cleanup();
// Do additional cleanup here.
};
};
class Level2DerivedClass : public Level1DerivedClass
{
Level2DerivedClass()
{
};
~Level2DerivedClass()
{
};
void Cleanup()
{
// Call my base cleanup.
Level1DerivedClass::Cleanup();
// Do additional cleanup here.
};
};
main()
{
Level2DerivedClass * derived2 = new Level2DerivedClass();
delete derived2;
return 0;
}
When I delete my derived class reference, I would EXPECT the flow would be as follows:
Level2DerivedClass destructor is executed.
Because Level1DerivedClass destructor is virtual, it would be executed.
Because BaseClass destructor is virtual, it would be executed.
Because BaseClass::Cleanup and Level1DerivedClass::Cleanup are both virtual, the call from the BaseClass 'this' pointer in the BaseClass destructor would executed the implementation of the most derived class - Level2DerivedClass::Cleanup.
Level2DerivedClass::Cleanup calls its parent's Cleanup implementation.
Level1DerivedClass::Cleanup calls its parent's Cleanup implementation.
What is happening is that it is calling the destructors for each level of inheritance (1 - 3) above the way I'm expecting. But when this->Cleanup() is called from the BaseClass destructor, it only executes its own implementation. I don't understand why this is happening because normally when you instantiate a derived class pointer, cast it as a base class pointer, and call a virtual method from the base class pointer (in this case, 'this'), it still runs the derived class implementation (the whole point of 'virtual', yes?). In my example, Level2DerivedClass::Cleanup and Level1DerivedClass::Cleanup never gets called.
The reason I'm setting it up this way is I want to be able to call my Cleanup code without having to destroy my object, which is why I'm abstracting it from the actual destructor body.
If you have suggestions on a more proper way to do this, I'm all ears. But I would also like an explanation of why my setup doesn't work - what am I misunderstanding?
Thank you in advance for your time.
The rule of thumb is: Never Call Virtual Functions during Construction or Destruction.
They don't behave as you might expect; as each destructor finishes, the dynamic type of this is effectively modified. From [class.cdtor] in the C++ standard:
When a virtual function is called directly or indirectly from a constructor (including the mem-initializer or
brace-or-equal-initializer for a non-static data member) or from a destructor, and the object to which the
call applies is the object under construction or destruction, the function called is the one defined in the
constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived
from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived
object.
The Proper Way Of Doing Things is: clean after yourself, and yourself only, in the destructor. Don't clean after your kids or your parents.
If you want to clean up things not from the destructor, You Are Doing It Wrong. In C++ we have this little thing called RAII, Resource Acquisition Is Initialization. But there's also its dual, which does not seem to have an officially sounding name, but here's something that could work: RDID, Resource Disposal Is Destruction.
Of course you don't have to adhere to the RAII/RDID philosophy, but that would be Not The C++ Way.
If I have a base class and a derived class, and I delcare the destructor in the parent virtual, but instantiate an object of type subclass, when destroyed it will invoke the parent destructor right(since virtual)? If I also declare a destructor in the derived class, will it call both destructors (base and derived). Thanks in advance :-).
The second part to my question is regarding the first. Why does the base class destructor need to be declared virtual. Don't constrcutors cycle up the hiearchy. They don't share the same name, so where's the need for it? Shouldn't it work the same for destrucotrs, or by default is only one called? Also does through late binding is it able to detect all the classes and object is made of?
EDIT: My question is not just about virtual destructors, but why does it need to be declared virtual, since they should all be called by default.
Yes, parent destructors will be called automatically.
The destructor should be virtualised so a derived instance can be destroyed properly by code that thinks it has a reference to a base class instance.
In very limited circumstances, it is OK not to virtualise, if you really need to save a few cycles on the vtable lookup.
The need for virtual destructors is because of polymorphism. If you have something like the following:
class A { ... };
class B : public A { ... };
void destroy_class(A* input)
{
delete input;
}
int main()
{
B* class_ptr = new B();
destroy_class(class_ptr); //you want the right destructor called
return 0;
}
While a bit of a contrived example, when you delete the passed-in pointer for the destroy_class() function, you want the correct destructor to get called. If the destructor for class A was not declared virtual, then only the destructor for class A would get called, not the destructor for class B or any other derived type of class A.
Stuff like this is very often a fact-of-life with non-template polymorphic data-structures, etc. where a single deletion function may have to delete pointers of some base-class type that actually points to an object of a derived type.
rubixibuc,
Yeah the subclasses destructor is invoked first, then it's superclass... then it's superclass, and so on until we get to Object's destructor.
More here: http://www.devx.com/tips/Tip/13059 ... it's worth the read... only a screen-full, but it's an INFORMATIVE screen-full.
This question may sound too silly, however , I don't find concrete answer any where else.
With little knowledge on how late binding works and virtual keyword used in inheritance.
As in the code sample, when in case of inheritance where a base class pointer pointing to a derived class object created on heap and delete operator is used to deallocate the memory , the destructor of the of the derived and base will be called in order only when the base destructor is declared virtual function.
Now my question is :
1) When the destructor of base is not virtual, why the problem of not calling derived dtor occur only when in case of using "delete" operator , why not in the case given below:
derived drvd;
base *bPtr;
bPtr = &drvd; //DTOR called in proper order when goes out of scope.
2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented].
3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call?
Fundamentaly i want to know who calls the dtor of the class when delete is used.
<h1> Sample Code </h1>
class base
{
public:
base(){
cout<<"Base CTOR called"<<endl;
}
virtual ~base(){
cout<<"Base DTOR called"<<endl;
}
};
class derived:public base
{
public:
derived(){
cout<<"Derived CTOR called"<<endl;
}
~derived(){
cout<<"Derived DTOR called"<<endl;
}
};
I'm not sure if this is a duplicate, I couldn't find in search.
int main()
{
base *bPtr = new derived();
delete bPtr;// only when you explicitly try to delete an object
return 0;
}
This is due to tha fact that in this case the compiler know everything about the object to be destructed which in this case is drvd and is of type derived. When drvd goes out of scope the compiler inserts code to call its destructer
delete is a keyword for compiler. When compiler see delete it inserts the code to call the destructer and the code to call operator delete to deallocate the memory.Please keep in mind that keyword delete and operater delete are different.
When compiler sees keyword delete being used for a pointer it needs to generate code for its proper destruction. For this it needs to know the type information of the pointer. The only thing the compiler know about the pointer is the pointer type, not the type of object to which the pointer is pointing to. The object to which the pointer is pointing to may be a base class or a derived class. In some cases the type of object may be very clearly defined for example
void fun()
{
Base *base= new Derived();
delete base;
}
But in most cases it is not, for example this one
void deallocate(Base *base)
{
delete base;
}
So the compiler does not know which destructer to call of base or of derived. This is the way then it works
If the Base class does not have a virtual function (member function or destructer). It directly insetrts thr code to call the destructer of base class
If the Base class has virtual functions, then the compiler takes the information of destructer from vtable.
If destructer is not virtual. The vtable will have the address of base destructer and thats what will be called. This is not right since the proper destructer is not being called here. This is why it is always recommended to declare destructer of base class as virtual
If the destructer is virtual the vtable will have correcte address of destructer and compiler will insert proper code over there
+1 Good question BTW.
Look at how the virtual mechanism works for a non destructor method and you'll find a destructor behaves no differently.
There are 2 mechanism in play which may confuse the issue a little
.
Firstly a mechanism that isn't virtual is happening on construction and destruction of an object. The object is constructed from base class to derived class, in that order, and when destructed the destructor order is the reversed, so derived to based class. Nothing new here.
Consider calling a non virtual method on a based class pointer to a derived class object, what happens? The base class implementation is called. Now consider calling a virtual method from a base class pointer to a derived class object, what happens? The derived version of the method is called. Nothing you didn't already know.
Lets now consider the destructor scenario. Call delete on a base class pointer to a derived class object which has a non virtual destructor. The base class destructor is called, and if the base class had been derived from another class, then it's destructor would get called next. Because the virtual mechanism isn't in play , the derived destructor won't be called because destruction starts from the destructor you call in the hierarchy and works it way down to the base class.
Now consider the virtual destructor case. delete is called on a based class pointer to a derived class object. What happens when you call any virtual method on a base class pointer? The derived version gets called. So our derived class destructor is called . What happens during destruction, the object destructs from derived destructor to base class, but this time we started the destruction at the derived class level because of the virtual method mechanism.
Why does a stack object with either a non virtual or virtual destructor destruct from derived to base class when it goes out of scope? Because the destructor of the declared class is called in this case and the virtual mechanism has nothing to do with it.
The compiler generates all necessary code to call destructors in the right order, whether it be a stack object or member variable going out of scope, or a heap object being deleted.
You instantiate the derived type, when it goes out of scope it calls the destructor, virtual or not.
The compiler will generate code which makes a call to the destructors. It does not all happen on compile time. Code generation does, but lookin up what the address of the dtor is happens at runtime. Think about the case where you have more then 1 derived type and you do the delete using a base pointer.
A base class destructor needs to be virtual to make a polymorphic delete call the dtor of the derived type.
If you want to find out more try overloading new and delete.
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.
For example
class Interface
{
virtual void doSomething() = 0;
};
class Derived : public Interface
{
Derived();
~Derived()
{
// Do some important cleanup...
}
};
void myFunc(void)
{
Interface* p = new Derived();
// The behaviour of the next line is undefined. It probably
// calls Interface::~Interface, not Derived::~Derived
delete p;
}
The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor.
You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor.
You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases.
[See item 4 in this article: http://www.gotw.ca/publications/mill18.htm]
I decided to do some research and try to summarise your answers. The following questions will help you to decide what kind of destructor you need:
Is your class intended to be used as a base class?
No: Declare public non-virtual destructor to avoid v-pointer on each object of the class *.
Yes: Read next question.
Is your base class abstract? (i.e. any virtual pure methods?)
No: Try to make your base class abstract by redesigning your class hierarchy
Yes: Read next question.
Do you want to allow polymorphic deletion through a base pointer?
No: Declare protected virtual destructor to prevent the unwanted usage.
Yes: Declare public virtual destructor (no overhead in this case).
I hope this helps.
* It is important to note that there is no way in C++ to mark a class as final (i.e. non subclassable), so in the case that you decide to declare your destructor non-virtual and public, remember to explicitly warn your fellow programmers against deriving from your class.
References:
"S. Meyers. More Effective C++, Item 33 Addison-Wesley, 1996."
Herb Sutter, Virtuality, 2001
C++ Faq, 20.7, "When should my destructor be virtual?"
The answers to this question, of course.
Yes it is always important. Derived classes may allocate memory or hold reference to other resources that will need to be cleaned up when the object is destroyed. If you do not give your interfaces/abstract classes virtual destructors, then every time you delete a derived class instance via a base class handle your derived class' destructor will not be called.
Hence, you're opening up the potential for memory leaks
class IFoo
{
public:
virtual void DoFoo() = 0;
};
class Bar : public IFoo
{
char* dooby = NULL;
public:
virtual void DoFoo() { dooby = new char[10]; }
void ~Bar() { delete [] dooby; }
};
IFoo* baz = new Bar();
baz->DoFoo();
delete baz; // memory leak - dooby isn't deleted
It is not always required, but I find it to be good practice. What it does, is it allows a derived object to be safely deleted through a pointer of a base type.
So for example:
Base *p = new Derived;
// use p as you see fit
delete p;
is ill-formed if Base doesn't have a virtual destructor, because it will attempt to delete the object as if it were a Base *.
It's not only good practice. It is rule #1 for any class hierarchy.
The base most class of a hierarchy in C++ must have a virtual destructor
Now for the Why. Take the typical animal hierarchy. Virtual destructors go through virtual dispatch just as any other method call. Take the following example.
Animal* pAnimal = GetAnimal();
delete pAnimal;
Assume that Animal is an abstract class. The only way that C++ knows the proper destructor to call is via virtual method dispatch. If the destructor is not virtual then it will simply call Animal's destructor and not destroy any objects in derived classes.
The reason for making the destructor virtual in the base class is that it simply removes the choice from derived classes. Their destructor becomes virtual by default.
The answer is simple, you need it to be virtual otherwise the base class would not be a complete polymorphic class.
Base *ptr = new Derived();
delete ptr; // Here the call order of destructors: first Derived then Base.
You would prefer the above deletion, but if the base class's destructor is not virtual, only the base class's destructor will be called and all data in derived class will remain undeleted.