Q:

Write a C++ Program to illustrate Abstract Base Class

belongs to collection: C++ Polymorphism Solved Programs

0

Write a C++ Program to illustrate Abstract Base Class. Here’s a Simple C++ Program to illustrate Abstract Base Class in C++ Programming Language.

What is Polymorphism in C++ ?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

 
 

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.


Virtual Function : :


A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don’t want static linkage for this function.


Below is the source code for C++ Program to illustrate Abstract Base Class which is successfully compiled and run on Windows System to produce desired output as shown below :

 

SOURCE CODE : :

/*  C++ Program to illustrate Abstract Base Class  */

#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area (void) =0;
};

class Rectangle: public Polygon {
  public:
    int area (void)
      { return (width * height); }
};

class Triangle: public Polygon {
  public:
    int area (void)
      { return (width * height / 2); }
};

int main ()
{
  Rectangle rect;
  Triangle trgl;
  Polygon * ppoly1 = &rect;
  Polygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  cout<<"\nExample to illustrate Abstract Base Class :: \n\n";
  cout << ppoly1->area() << "\n";
  cout << ppoly2->area() << "\n";
  return 0;
}

OUTPUT : :


/*  C++ Program to illustrate Abstract Base Class  */

Example to illustrate Abstract Base Class ::

20
10

Process returned 0

Above is the source code and output for C++ Program to illustrate Abstract Base Class which is successfully compiled and run on Windows System to produce desired output.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Program to illustrate an example of Pure Virtu... >>
<< C++ Program to show an Example of Pointers to base...