Example of inheritance in C++


Running

Source Code

main.cpp

#include <iostream>
#include "square.h"
using namespace std;
int main(int argc, char** argv)
{
  RectangleParent rectangleParent(10.2, 7.9);
  SquareChild squareChild(5);
  cout << "RectangleParent rectangleParent(10.2, 7.9)\n\n";
  cout << "Side A = " << rectangleParent.getSideA() << endl << "Side B = " << rectangleParent.getSideB();
  cout << "\nArea = " << rectangleParent.getArea();
  cout << "\n\nSquareChild squareChild(5)\n\n" << "Side = " << squareChild.getSideA(); //could be either getSideA or getSideB here (they are the same value for a Square)
  cout << "\nArea = " << squareChild.getArea();
	
	SquareParent squareParent(7);
	RectangleChild rectangleChild(2.4, 3);
	cout << "\n\nSquareParent squareParent(7)\n\n";
	cout << "Side = " << squareParent.getSide() << endl << "Area = " << squareParent.getArea();
  cout << "\n\nRectangleChild rectangleChild(2.4, 3)\n\n" << "Side A = " << rectangleChild.getSide();
  cout << "\nSide B = " << rectangleChild.getSideB();
  cout << "\nArea = " << rectangleChild.getArea();
  return 0;
}

square.h

#ifndef SQUARE_H
#define SQUARE_H

class RectangleParent
{
  public:
    RectangleParent(const double a, const double b)
    {
      sideA = a;
      sideB = b;
    }
    double getSideA()
    {
      return sideA;
    }
    double getSideB()
    {
      return sideB;
    }
    double getArea()
    {
      return sideA * sideB;
    }
  private:
    double sideA;
    double sideB;
};

class SquareChild : public RectangleParent
{
	public:
	  SquareChild(const int side) : RectangleParent(side, side) {}
};

class SquareParent
{
  public:
    SquareParent(const double s)
    {
      side = s;
    }
    double getSide()
    {
      return side;
    }
    double getArea()
    {
      return side * side;
    }
  private:
    double side;
};

class RectangleChild : public SquareParent
{
  public:
    RectangleChild(const double a, const double b) : SquareParent(a)
    {
      sideB = b;
    }
    double getSideB()
    {
      return sideB;
    }
    double getArea()
    {
      return getSide() * sideB;
    }
  private:
    double sideB;
};

#endif
,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: