0 votes
in C Plus Plus by

Give an example of Run-time Polymorphism/Virtual Functions.

1 Answer

0 votes
by

class SHAPE{

                  public virtual Draw() = 0; //abstract class with a pure virtual method

 };

 class CIRCLE: public SHAPE{

                  public int r;

                  public Draw() { this->drawCircle(0,0,r); }

 };

class SQUARE: public SHAPE{

               public int a;

               public Draw() { this->drawSquare(0,0,a,a); }

 };

 

 int main()

 {

                SHAPE shape1*;

                SHAPE shape2*;

  

                CIRCLE c1;

                SQUARE s1;

  

               shape1 = &c1;

              shape2 = &s1;

             cout<<shape1->Draw(0,0,2);

             cout<<shape2->Draw(0,0,10,10);

 }

In the above code, the SHAPE class has a pure virtual function and is an abstract class (cannot be instantiated). Each class is derived from SHAPE implementing Draw () function in its own way.

Further, each Draw function is virtual so that when we use a base class (SHAPE) pointer each time with the object of the derived classes (Circle and SQUARE), then appropriate Draw functions are called.

Related questions

0 votes
asked Dec 21, 2023 in C Plus Plus by GeorgeBell
+1 vote
0 votes
asked Apr 30, 2021 in JAVA by rajeshsharma
...