Inheritance and composition (point, square, cube)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  #include <iostream>
#include <math.h>

using namespace 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
So basically, my program is like half composition half inheritance?
Yes, it looks that way to me.

Also, your program does not need Point p1, p2; on line 38.
Last edited on
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/195750/
Topic archived. No new replies allowed.