destructors

Hej every one,
Could any one explain me what is the meaning of virtual destructor?

virtual ~G4VUserDetectorConstruction ()

Thanks in advance
do you know what a virtual method is?
Here it goes...

@kfmfe04
do you know what a virtual method is?

Yes, first you need to know what a virtual function is. Also, you need to know what (public) inheritance is.

Basically, a virtual function is a function in a base class whose implementation is typically overloaded in a derived class that publicly inherits from the base class.

If you then call a virtual function through a pointer or reference to a BASE class, that is bound to a DERIVED class, you then invoke the implementation of that DERIVED class NOT the BASE class (this is called polymorphism).

All derived classes are implemented in terms of their base class. If you call a destructor for a derived object bound to a pointer or reference to its base class, the BASE class destructor will be invoked, NOT the DERIVED class destructor, hence the derived class part of the object will be leaked (i.e., in memory).

Therefore, you need to declare the BASE class constructor virtual so that when you destroy a DERIVED class object through a reference or pointer to its BASE class, (a polymorphic call to) the DERIVED class destructor is invoked, making sure that all of your object is deleted and that no part of the memory storing the object is leaked.

Hope that helps.
Last edited on
Thanks for your reply, So you mean that whenever I have polymorphism and derivd

classes
from an Abstract Base Class I have to use virtual constructors and

destructors in my Abstract Base Class?
if you want the destructors to all of the base classes above you called (almost always yes in real life coding), you want to make your uppermost base destructor virtual

sometimes, there is some optimization possible by not using virtual destructors - I used to follow some of these rules until after a while, I began to notice that in the heat of coding, I'm not disciplined enough ask myself every time, do I need all my destructors to be called and have I made my destructors virtual?

so to guarantee that I don't get memory leaks caused by non-virtual destructors, as a principle, once I begin to subclass, I make the base class destructor virtual

btw, there is no such thing as a virtual constructor
Topic archived. No new replies allowed.