Virtual Constructor in C++

There is no concept of Virtual Constructor in C++ because to create an object we need to know the exact type of it and in case of Virtual function we only have an interface to call and not the type of object.


But using clone and create function we can get the effect of a Virtual Constructor. These functions will be pure virtual member functions in the Base Class. Virtual Clone function will use copy constructor to make object and Virtual Create function will use constructor to create an object.

We have a base class Shape. Shape has got member variable mycolor. This is added to show that the cloned object will have the same color as of the object from which it is cloned and the newly created object will not have the same color.
The default value of mycolor is No-Color. Also shape class is an Abstract class with two pure virtual functions:-

virtual Shape* clone()  const=0;
virtual Shape* create() const=0

A derived class name Circle is also defined which overrides these pure virtual functions.
The clone function of Circle class created a new object by calling the default copy constructor of the Circle class.
The create function of Circle class created a new object by calling the default constructor of the Circle Class.

Shape* and Circle* are also know as Covariant Return Types

The Code:-



 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>

class Shape
{
public:

Shape():mycolor("No-Color"){std::cout << "Shape() Constructor Called\n\n";};

virtual ~Shape(){std::cout << "Shape~ Destrutor Called\n\n";}
virtual Shape* clone() const=0;
virtual Shape* create() const=0;

std::string mycolor;
void setcolor(std::string color) {mycolor = color;};
std::string const getcolor() {return mycolor;};
};


class Circle : public Shape
{
public:
Circle() {std::cout << "Circle() Constructor Called\n\n";}
// Circle (const Circle &) {std::cout << "Circle Copy Constructor Called\n\n";}

~Circle(){std::cout << "Circle~ Destrutor Called\n\n";}
Circle* clone() const;
Circle* create() const;
};


Circle* Circle::clone() const
{
return new Circle(*this); //Copy Constructor will be called
}

Circle* Circle::create() const
{
return new Circle(); //Constructor will be called
}


int main()
{

Shape *s = new Circle();
s->setcolor("RED");
std::cout << "My color is = " << s->getcolor() <<"\n\n";

Shape* s1 = s->clone(); // Here the Object is Cloned so color should be RED
std::cout << "My color is = " << s1->getcolor() <<"\n\n";

Shape* s2 = s->create(); // Here the Object is Created so color should NOT be RED
std::cout << "My color is = " << s2->getcolor() <<"\n\n";

delete s1;
delete s2;

getchar();
return 0;
}



The Output is :

Comments

Popular Posts