virtual functionsthe keyword virtual was


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();

}

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: virtual functionsthe keyword virtual was
Reference No:- TGS0309460

Expected delivery within 24 Hours