For my assigment, I have to create classes for point, square and cube, by inheritance and by composition. I did the inheritance part, but I dont really understand composition. Ive been reading alot on the subject and cant get my head around the composition. Heres my code, done with inheritance (my code is written in french (basically carre=square and aire=area).
Any ideas how I could transform this to a program using composition?
Thank you very much
#include <iostream>
#include <math.h>
usingnamespace std;
class Point {
public:
int x1,y1;
void set_values (int x, int y)
{x1=x; y1=y;}
};
class Carre {
public:
Point p1, p2;
int length(){return sqrt((p2.x1 - p1.x1) * (p2.x1 - p1.x1) + (p2.y1 - p1.y1) * (p2.y1 - p1.y1));}
int aire()
{return length() * length();}
};
class Cube: public Carre {
public:
int volume()
{return aire() * length();}
};
int main()
{
cout << "***** Point, carre et cube en heritage *****" << endl;
cout << endl;
int a,b,c,d;
cout <<"Coordonner en X du premier point: "; cin>>a;
cout <<"Coordonner en Y du premier point: "; cin>>b;
cout <<"Coordonner en X du deuxieme point: "; cin>>c;
cout <<"Coordonner en Y du deuxieme point: "; cin>>d;
Point p1,p2;
Carre carre1;
Cube cube1;
carre1.p1.set_values(a,b);
carre1.p2.set_values(c,d);
cube1.p1.set_values(a,b);
cube1.p2.set_values(c,d);
cout << endl;
cout <<"********************************************" << endl;
cout << "L'aire du carre est de " <<carre1.aire() << endl;
cout << "Le volume du cube est de "<<cube1.volume() << endl;
}
It seems to me like your Cube class inherits from Square, and Square is composed with Points. I take the word composition in your situation to be similar in definition to function composition in mathematics. f( g(x) ) is f composed onto g, meaning f uses g as a base to build from. In your case Square is built from the base of two points. Seems like composition to me. https://en.wikipedia.org/wiki/Composition_over_inheritance