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

Why constructor can not be defined as virtual

Why constructor can not be defined as virtual?

Thanks

littlestone
Light Poster
42 posts since Mar 2008
Reputation Points: 14
Solved Threads: 6
 

google is a wonderful invention :)

A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor.

http://www.codersource.net/published/view/325/virtual_functions_in.aspx

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Thank you so much.

littlestone
Light Poster
42 posts since Mar 2008
Reputation Points: 14
Solved Threads: 6
 

I think the only way to create a "virtual constructor" is to make a virtual method that returns the object inquestion, where derived classes return a copy of their type instead of the base classes return implementation.

By casting a derived type to a base type and invoking the virtual constructor method, you're constructing an object virtually, therefore it's safe to say it is a "virtual constructor".

Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
 

constructor can't be defined as virtual bcuz if a class contains virtual function then the associate vtable must be initiated by the constructor of that class.if we define constructor as virtual then it creates a problem that who initiates that vtable.

avikmukherjee
Newbie Poster
1 post since May 2011
Reputation Points: 10
Solved Threads: 0
 

Nice reply to 3-year-old thread. I suspect the OP already knows that by now.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You