Virtual Functions
The keyword virtual was previously used to resolve ambiguity for a class derived from two classes, both having a common ancestor. These classes are known as virtual base classes. This time it helps in implementing the idea of polymorphism with class inheritance. The function of the base class can be declared with the keyword virtual. The program with this change and its output is given below.
class Shape
{
public :
virtual void print()
{
cout << " I am a Shape " << endl;
}
};
class Triangle : public Shape
{
public :
void print()
{
cout << " I am a Triangle " << endl;
}
};
class Circle : public Shape
{
public :
void print()
{
cout << " I am a Circle " << endl;
}
};
void main()
{
Shape S;
Triangle T;
Circle C;
S.print();
T.print();
C.print();
Shape *ptr;
ptr = &S;
ptr -> print();
ptr = &T;
ptr -> print();
ptr = &C;
ptr -> print();
}