Devika said:
hi,
I understand the need of virtual destructor.but virtual constructor is
not supported in c++.but basically why we need to have virtual
constructor??
It makes no sense for a C++ constructor to be virtual, because the
exact type of an object is statically obvious at compile time. Based on
the declared, manifest type, the compiler knows exactly what
constructors have to be called and in what order.
A virtual destructor is needed so you can destroy an object through a
base class pointer. You invoke ``delete b;'' on a ``Base *b'' which
might actually be pointer to a Derived. The compiled code has to
properly destroy that object regardless of its type, and the virtual
destructor mechanism does that.
There is sometimes a need to construct an object whose type is not
known. For example, suppose you have some program that lets the user to
enter a class name as a string, like "wizard" or "warrior". You parse
the string, and based on what is parsed, you have to construct
different types of objects.
There are a number of ways to do that kind of thing. One way is the
Abstract Factory pattern. You use the run-time data (string or
whatever) as a key to fetch a factory from dictionary of factories.
Then you call the virtual functions on the factory to make objects of
that factory's type for you.
You may also need a mechanism to deal with construction parameters. The
factory interface may have to take some kind of abstract list of
keyword-value pairs. Each implementation of that interface will have to
parse from that structure the things it knows about, perform the
appropriate conversions, and then invoke the constructor with the right
arguments. Or perhaps internally choose from among several different
overloads of the constructor.