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.
Shape* and Circle* are also know as Covariant Return Types
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.
The Code:-
1 | #include <iostream> |
The Output is :
Comments
Post a Comment