3

Is there any need of Virtual Constructors? If so can any one post a scenario?

juan
  • 80,295
  • 52
  • 162
  • 195
Diwakar
  • 71
  • 1
  • 3
  • 7
  • You need to add more information to this question - people don't know exactly how to answer it. – Mark Ingram Sep 16 '08 at 10:37
  • can constructor be virtual ? i don't think so ..we can have virtual destructor but not virtual constructor in c++ as far . – rforritz Jun 26 '13 at 19:14

9 Answers9

8

If you are talking about virtual destructors in C++ (there isn't any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically.

class A
{
  ~A();
}

class B : public A
{
  ~B();
}

A* pB = new B();
delete pB; // NOTE: WILL NOT CALL B's destructor

class A
{
  virtual ~A();
}

class B : public A
{
  virtual ~B();
}

A* pB = new B();
delete pB; // NOTE: WILL CALL B's destructor

Edit: Not sure why I've got a downvote for this (would be helpful if you left a comment...) but have a read here as well

http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230
  • 1
    ...Probably downvoted because your answer, while correct, is unrelated to the question. Not by me, BTW... – Roddy Oct 26 '08 at 10:54
3

As always: look up at C++ FAQ lite: virtual functions.

It will explain not only "virtual constructor" but destructors/functions too!

This of course, if you wanted C++ in the first place...

Marcin Gil
  • 68,043
  • 8
  • 59
  • 60
3

There are plenty of scenarios, for example if you want to create GUIs for more than one environment. Let's say you have classes for controls (“widgets”) but each environment actually has its own widget set. It's therefore logical to subclass the creation of these widgets for each environment. The way to do this (since, as has been unhelpfully pointed out, constructors can't actually be virtual in most languages), is to employ an abstract factory and the above example is actually the standard example used to describe this design pattern.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

Delphi is one language that supports virtual constructors.

Typically they would be used in a class factory type scenario where you create a meta type i.e. that is a type that describes a type. You would then use that meta type to construct a concrete example of your descendant class

Code would be something like....

type
  MyMetaTypeRef = class of MyBaseClass;

var
  theRef : MyMetaTypeRef;
  inst : MyBaseClass;
begin 
  theRef := GetTheMetaTypeFromAFactory(); 
  inst := theRef.Create(); // Use polymorphic behaviour to create the class
Tim Jarvis
  • 18,465
  • 9
  • 55
  • 92
1

In what language? In C++ for example the constructors can not be virtual.

grigy
  • 6,696
  • 12
  • 49
  • 76
0

The constructor can not be virtual by definition. At the time of constructor call there is no object created yet, so the polymorphism does not make any sense.

grigy
  • 6,696
  • 12
  • 49
  • 76
  • Thats simply not true. Construction certainly can be virtual, the whole idea is to be able to declare a variable of type baseclass and construct it from a different concrete class. Delphi is one language for example that allows virtual constructors. – Tim Jarvis Sep 16 '08 at 23:08
0

In C++, there's no reason for constructors to ever be virtual, because they are static functions. That means they're statically bound, so you have to identify the very constructor function you're calling in order to call it at all. There's no uncertainty and nothing virtual about it.

This also means that, no matter what, you need to know the class that your object is going to be. What you can do, however, is something like this:

Superclass *object = NULL;
if (condition) {
    object = new Subclass1();
}
else {
    object = new Subclass2();
}
object.setMeUp(args);

... have a virtual function and call it after constructon. This is a standard pattern in Objective-C, in which first you call the class's "alloc" method to get an instance, and then you call the initilializer that suits your use.

The person who mentioned the Abstract Factory pattern is probably more correct for C++ and Java though.

easeout
  • 8,665
  • 5
  • 43
  • 51
  • Pity C++ classes aren't objects.... ----------------- In C++, there's no reason for constructors to ever be virtual, – David Jul 27 '09 at 19:22
-1

In C++, all constructors are implicitly virtual (with a little extra). That is, the constructor of the base class is called before that of the derived class. So, it's like they're sort of virtual. Because, in a virtual method, if the derived class implements a method of the same signature, only the method in the derived class is invoked.

However, in a constructor, BOTH METHODS ARE INVOKED (see example below).

For a more complete explanation of why this is so, please see Item 9 of Effective C++, Third Edition, By Scott Meyers (Never call a virtual function during construction or destruction). The title of the item may be misleading in relation to the question, but if you read the explanation, it'll make perfect sense.

#include <iostream>
#include <vector>

class Animal {

    public:

        Animal(){
            std::cout << "Animal Constructor Invoked." << std::endl;
        }

        virtual void eat() {
            std::cout << "I eat like a generic animal.\n";
        }

        //always make destructors virtual in base classes
        virtual ~Animal() {

        }

};

class Wolf : public Animal {

    public:

        Wolf(){
            std::cout << "Wolf Constructor Invoked." << std::endl;
        }

        void eat() {
            std::cout << "I eat like a wolf!" << std::endl;
        }

};


int main() {

    Wolf wolf;
    std::cout << "-------------" << std::endl;
    wolf.eat();

}

Output:

Animal Constructor Invoked.
Wolf Constructor Invoked.
-------------
I eat like a wolf!
Homer6
  • 15,034
  • 11
  • 61
  • 81
  • "In C++, all constructors are implicitly virtual" -- I am curious, whether you can point me at any literature that states this. – Pradyot May 01 '13 at 17:51
  • As stated above, Item 9 in Scott Meyers book outlines and explains this. One exception to this is in virtual base classes. See section 15.2.4.1 of "The C++ Programming Language, Special Edition" by Bjarne Stroustrup for a description of virtual base classes and how "the language ensures that a constructor of a virtual base is called exactly once". – Homer6 May 01 '13 at 20:22
-2

Virtual constructors dont make sense in C++ . THis is because in C++ constructors do not have a return value . In some other programming languages this is not the case . In those languages the constructor can be called directly and the constructor has a return value . This makes them useful in implementing certain types of desgin patterns . In C++ however this is not the case .

rockstar
  • 3,512
  • 6
  • 40
  • 63
  • You are right when you say Virtual constructors dont make sense in C++. But it likely has nothing to do with return values. – Pradyot May 01 '13 at 17:49