PDA

View Full Version : virtual constructor



vermarajeev
30th September 2006, 13:57
Hi guys,

1) Why don't we have virtual constructors?
2) What is the main use of pure virtual destructor?

Please explain giving some examples as I need to have visualization for this....

Any comment will be highly appreciated...

Thankx

wysota
30th September 2006, 14:23
1) Why don't we have virtual constructors?
What would we need it for? You need virtual methods only if you want to make sure that if you call that method, the implementation from the correct class is used, no matter what points to the object.


struct A {
void f1() { cout << "A::f1" << endl; }
virtual void f2() { cout << "A::f2" << endl; }
};

struct B : public A {
void f1() { cout << "B::f1" << endl; }
void f2() { cout << "B::f2" << endl; }
};

Now if you do this:

A *ptr = new B;
ptr->f1();
ptr->f2();
you'll receive:
A::f1 (non-virtual, called according to the pointer)
B::f2 (virtual, called according to the object class)

It doesn't make much sense with constructors, as constructors are always called according to the class (you might say they are implicitely virtual), because you always specify what object you want to create ("new B" in the above mentioned example).


2) What is the main use of pure virtual destructor?
Virtual destructor is required to make sure that the correct destructor gets called if you have virtual methods.

Pure virtual destructor (as every other pure virtual method) assures you can't make an instance of this class - you have to subclass and implement the method there and you'll be able to create instances of the subclass only.