C++

Topic: Constructors and destructors

What is virtual Destructors ?

To build an object the constructor must be of the same type as the object and because of this a constructor cannot be a virtual function. But the same thing does not apply to destructors. A destructor can be defined as virtual or even pure virtual. You would use a virtual destructor if you ever expect a derived class to be destroyed through a pointer to the base class. This will ensure that the destructor of the most derived classes will get called: A* b1 = new B;delete b1; If A does not have a virtual destructor, deleting b1 through a pointer of type A will merely invoke A's destructor. To enforce the calling of B's destructor in this case we must have specified A's destructor as virtual: virtual ~A(); It is a good idea to use a virtual destructor in any class that will be used as an interface (i.e., that has any other virtual method). If your class has no virtual methods, you may not want to declare the destructor virtual because doing so will require the addition of a vtable pointer.  The destructor is called every time an object goes out of scope or when explicitly deleted by the programmer(using operator delete). The order in which local objects are implicitly deleted when the scope they are defined ends is the reverse order of their creation: void f(){    string a(.some text.);    string b = a;    string c;    c = b;} At the end of function f the destructors of objects c, b, a (in this order) are called and the same memory is deallocated three times causing undefined and wrong behavior. Deleting an object more than one time is a serious error. To avoid this issue, class string must be provided with a copy constructor and a copy assignment operator which will allocate storage and copy the members by values. The same order of construction/destruction applies for temporary objects that are used in expressions or passed as parameters by value. However, the programmer is usually not concerned with temporary objects since they are managed by the C++ compiler.  Unlike local objects, static objects are constructed only the first time their definition is reached and destroyed at the end of the program.  By the way, if you liked the details about how C++ works, you might enjoy Scott Meyer's excellent book on C++:

Browse random answers: