Pages

Saturday, July 29, 2017

C++ Inheritance Example

Example of C++ Inheritance (Base class: Shape, Derived class: Square)


A class can be derived from other class. Derived class also inherits data and functions from base class. Consider a base class Shape and its derived class Square

Following C++ program demonstrate how Square class is derived from base class Shape.


#include <iostream>
using namespace std;

class Shape {
  protected:
     int height;

  public:
     void setHeight(int h){
        height = h;
     }
};

// Derived class from Shape

class Square: public Shape {
  public:
     int findArea() {
        return (height * height);
     }
};

int main(void) {
  Square Sqr;

  Sqr.setHeight(5);

  // Print the area of the Square
  cout << "Area of Square:" << Sqr.findArea();

  return 0;
}

Output of program

Area of Square: 25

No comments:

Post a Comment