Q:

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

belongs to collection: C++ Polymorphism Solved Programs

0

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

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 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.

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

total answers (1)

Write a C++ Program to illustrate Abstract Base Cl... >>
<< C++ Program to illustrates the use of Virtual base...