Square and Cube Class in C++
Posted by Samath
Last Updated: January 01, 2015

Write 2 classes named Square and Cube.

The class Cube inherits the class Square.

The class Square has 2  integers attributes named x and y. It has one constructor that takes two integers and assigns them to x and y. Finally it has 1 method named computeArea the returns an integers after calculating the area of the square. The method fets no arguments.

The class Cube has one field which is a private integer named z. It has one constructor takes three integer arguments and calls its super-class constructor to assign x and y values, and then it assigns z value in its own constructor. Finally, it overrides the method computeArea

Code:

#include <iostream>
 
using namespace std;


class Square 
{
public:
	Square(int x1, int y1);


	int computeArea();

	private:
	int x;
	int y;

};

Square::Square(int x1, int y1)
{
	x = x1;
	y= y1;
}

int Square::computeArea()
{
	return x * y;
}


class Cube: public Square
{
   public:
	   Cube(int z1,int x, int y):Square(x, y)
	   {
		   z = z1;
	   }

	   int computeArea()
	   {
		   return Square::computeArea() * z; 
	   }
      
   private:
	   int z;

};



int main(int argc, char *argv[])
{
	    Square square(10,10);
        Cube cube(10,10,10);
 
		cout<<"Square's area: "<< square.computeArea();
        cout<<"\nCube's area: "<< cube.computeArea();

	return 0;	
}