Write a C++ Program to illustrate Abstract Base Class

By | January 3, 2017

Illustrate Abstract Base Class


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++ ?


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.

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach upto you in the short interval.


Thanks for reading the post….

Leave a Reply