DIR Return Create A Forum - Home
---------------------------------------------------------
ifaq
HTML https://ifaq.createaforum.com
---------------------------------------------------------
*****************************************************
DIR Return to: C/C++ related questions
*****************************************************
#Post#: 7--------------------------------------------------
Constructors/Destructors and virtual
By: avinash.srin Date: August 25, 2011, 9:43 am
---------------------------------------------------------
Can you make constructors and destructors virtual? Explain the
background in each case.
#Post#: 18--------------------------------------------------
Re: Constructors/Destructors and virtual
By: avinash.srin Date: August 26, 2011, 5:27 am
---------------------------------------------------------
No we cant make virtual constructors. It's illegal and not
required as well. A constructor is invoked at the time of object
creation. Only after that a vtable and virtual pointer are
created. Hence, there wont be any use of having a virtual
constructor.
However, it's possible to have virtual destructors and advisable
to be used in classes with at least one virtual function. Having
virtual functions indicate that a class is meant to act as an
interface to derived classes, and when it is, an object of a
derived class may be destroyed through a pointer to the base.
For example:
[code]
class Base {
// ...
virtual ~Base();
};
class Derived : public Base {
// ...
~Derived();
};
void f()
{
Base* p = new Derived;
delete p;
is called
}
[/code]
Had Base's destructor not been virtual, Derived's destructor
would not have been called - with likely bad effects, such as
resources owned by Derived not being freed. Note that a base
type pointer is pointing to a derived type object in the
example.
*****************************************************