Can we have "Virtual Constructors"?

Answer Posted / bharat

People have already posted the answer in brief, however for
a newbie, this might not be enough... Hence posting this
thread...

If you are referring to constructors as in pure C++, then
there is no such concept as "virtual" constructors. A
constructor is responsible for creation of the particular
object, and hence cannot be "virtual".

It cannot be so, because a virtual function allows the
actual function call to be "deeper" in the hierarchy than
the type through which it is being called. for example, you
can have a base pointer through which a virtual call is made
to a derived object's function code (Derived class is
"deeper" than base class")

Since the constructor is responsible for creation of the
object itself, the function call being "deeper" than the
type being created does not make any sense. Hence a
constructor is always "local", and virtual constructor
concept does not exist.


However, in the domain of design patterns, there is such a
concept as Virtual Constructor or Factory Method. You can
find more information on this concept in "Thinking in C++
Volume 2" (A superb and Free ebook by Bruce Eckel) at the
location

http://www.planetpdf.com/developer/article.asp?ContentID=6634

Hope this is useful...

Is This Answer Correct ?    9 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is implicit conversion/coercion in c++?

644


What is the difference between the functions memmove() and memcpy()?

624


What is a rooted hierarchy?

673


What is general form of pure virtual function? Explain?

506


What is a template in c++?

633






What are the methods of exporting a function from a dll?

646


What is the importance of mutable keyword?

577


What is virtual methods?

653


Can c++ be faster than c?

596


What are guid? Why does com need guids?

566


Explain the difference between overloading and overriding?

605


What are enumerations?

651


What is the difference between the functions rand(), random(), srand() and randomize()?

724


Explain one method to process an entire string as one unit?

922


How do we balance an AVL Tree in C++?

630