C++/c++

Advertisement


Question
why virtual cons. is not possible but virtual cons. is posiable in c++

Answer
By "cons" I presume you mean "constructor" and not the not totally unrelated "cons" constructs used by Lisp and other programming languages (see http://en.wikipedia.org/wiki/Cons). A more common short form for constructor is "ctor" (and "dtor" for destructor).

Virtual constructors are not directly supported by C++. To take advantage of polymorphism - i.e. virtual member functions - you require an _existing_ created object that may be referenced via a reference to a base class or interface of the object. In the case of C++ we do not have explicit interface types but can use abstract base classes consisting wholly of pure virtual function declarations, and a reference in C++ can be either a C++ reference or pointer to an object.

You must _always_ create an object by specifying the exact type you require - how else would the compiler know what you wanted to create? However if you are creating an object dynamically in C++ then you can assign the returned object pointer from the scalar new operator to a pointer to a base of the created type:

   class Base { ... };

   class Derived : public Base { ... };

   ...

   Base * p( new Derived );

Because you always request an object by its exact type there can be no use for polymorphism and in fact the 'machinery' required to support polymorphic behaviour is fixed up during object construction (if the object has any virtual functions - either directly declared or inherited). The polymorphic support 'machinery' is torn down during destruction - however in this case we do have a fully created object and it may be being referred to through a base reference (or pointer) so we can have and do use virtual destructors.

The effect of polymorphic constructors can be simulated using virtual member functions that return new instances of some type that is a sub type of some base type:

   class Base
   {

   ...

   public:
       virtual Base * Clone() const = 0; // pure virtual
   
       virtual ~Base() {}

   ...

   };


   class Derived1 : public Base
   {

   ...

   public:
       virtual Derived1 * Clone() const;
   
       virtual ~Derived1();

   ...

   };


   class Derived2 : public Base
   {

   ...

   public:
       virtual Derived2 * Clone() const;
   
       virtual ~Derived2();

   ...

   };


   Derived1 * Derived1::Clone() const
   {
       return new Derived1(*this);
   }
   
   Derived1::~Derived1()
   {
       ...
   }


   Derived2 * Derived2::Clone() const
   {
       return new Derived2(*this);
   }
   
   Derived2::~Derived2()
   {
       ...
   }

The above shows parts of three classes making up a class hierarchy (which in reality may be spread across several source files). Ellipsis ( ... ) are used to show areas of potentially un shown code. The Base class declares a pure virtual Clone member function that returns a pointer to a Base object that is intended to be a new clone (i.e. copy) of the object whose pointer was passed in.

The classes Derived1 and Derived2 derive publicly from Base and override and define the Clone member function. They also define (virtual) destructors and are assumed to be copy constructable.

The overrides of the virtual Base::Clone member return a new copy of the object Clone is called on.

One thing that may surprise you is that the return types from the Derived1::Clone and Derived2::Clone overrides are Derived1 * and Derived2 * rather than Base *. This is allowed by C++ as Derived1 and Derived2 are derived from Base - such variations in override return types is called covariant return types. Note that some older compilers may not support this feature (e.g. MSCV++ 6.0 and earlier). If you have a compiler that does not support covariant return types then change Derived1::Clone and Derived2::Clone to return Base * as declared for the Base::Clone member function.

This general technique can be used to create objects other than copies - e.g. a Create virtual function that creates default constructed objects or objects constructed from some set of parameters common to all types in the hierarchy.

For a similar example see the C++ FAQ lite FAQ 20.8 "What is a virtual constructor" at:

   http://www.parashift.com/c++-faq-lite/virtual-functions.html .  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.