Why cant we have a virtual constructor?

All the materials give somewhat similar anwer to this question. "First the VPTR Pointer is initialised to it's proper VTABLE by the contructor which is automatically done by the compiler ,,,," or "You don’t ever want to be able to make a call to a virtual function before the VPTR is properly initialized. Of course, the place where initialization can be
guaranteed is in the constructor, ....." or something similar to this.

My doubt is whether the constructor in question base class constructor???

Recommended Answers

All 3 Replies

Making constructors virtual doesn't make sense.
In inheritance hierarchy objects are constructed from the base down to the lowest derived class. Making constructor virtual means that you would be using a derived class constructor before a base was even created.
What's the purpose of using a derived class if the base hasn't been created yet?

Agreed to that ... Can you make it clear, when the initialization of virtual pointer with the address of virtual table will take place???

You can get the effect of Virtual Constructor by using Factory design pattern...... which doesn't violates the objected oriented rules specifically inheritance structure........ but its helpful. and some times needed....

The vptr not necessarily initialized by the compiler in the constructor it might be initialized during the construction... its totally the implementation dependent thing... i.e. to preserve the polymorphic behavior. Some compiler might not use Vptr and vTable to hold the virtual functions entries..... they might use some other structure to behave polymorphically.......

check out http://www.daniweb.com/techtalkforums/thread18399.html.
get some idea about virutal constructor kind stuff.
Hope you get the basic idea..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.