C++ Program to show an Example of Pointers to base class

By | 03.01.2017

Example of Pointers to base class


Write a C++ Program to show an Example of Pointers to base class. Here’s a Simple C++ Program to show an Example of Pointers to 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 show an Example of Pointers to base class which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


/*  C++ Program to show an Example of Pointers to 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; }
};

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

class Triangle: public Polygon {
  public:
    int area()
      { 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<<"\n\tPointers to base class...\n\n";
  cout << rect.area() << "\n";
  cout << trgl.area() << "\n";
  return 0;
}

OUTPUT : :


/*  C++ Program to show an Example of Pointers to base class  */

        Pointers to base class...

20
10

Process returned 0

Above is the source code and output for C++ Program to show an Example of Pointers to 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….

3.5 2 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments