954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Virtual constructor

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???

dilip.mathews
Junior Poster in Training
89 posts since Jun 2006
Reputation Points: 16
Solved Threads: 3
 

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?

Grunt
Junior Poster
152 posts since Jul 2006
Reputation Points: 197
Solved Threads: 12
 

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

dilip.mathews
Junior Poster in Training
89 posts since Jun 2006
Reputation Points: 16
Solved Threads: 3
 

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..

Laiq Ahmed
Junior Poster
148 posts since Jun 2006
Reputation Points: 113
Solved Threads: 20
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You