I am struggling to understand a concept when using composition in c++. I have created a demo program to illustrate my confusion. The program might seem a bit pointless but its only purpose is to illustrate my question.
#include <iostream>
using namespace std;
class Shape
{
private:
double width;
double length;
double area;
public:
void init(int, int);
double getArea() const
{
return area;
}
};
class Rectangle : public Shape
{
private:
public:
};
void Shape::init(int wid, int hei)
{
width = wid;
length = hei;
area = length * width;
}
class ShapeArea
{
private:
Rectangle rectShape;
int area;
public:
ShapeArea()
{
area = rectShape.getArea();
}
};
int main()
{
Rectangle rectShape;
rectShape.init(5, 5);
ShapeArea newshape;
getchar();
return 0;
}
In this program I create a rectShape object, and initialize its width and length as 5, and the program calculates its area, and stores them all as member variables.
Now I have created a class called ShapeArea, and using composition given it Rectangle object called rectShape.
class ShapeArea
{
private:
Rectangle rectShape;
int area;
public:
ShapeArea()
{
area = rectShape.getArea();
}
};
In its constructor, I am allowed to call rectShape.getArea(), because getArea() is a member function of class Rectangle (derived from class Shape). The problem I am facing is that the rectShape object it is using to call this function is filled with random values in memory.
So my question is, in this design, how do I tell class ShapeArea that the rectShape Rectangle object I want to call the getArea() function of, is the one I have already created earlier in the program? Ideally I want the newshape object I create to have the value "25" as area.
I hope this question is clear.
Thanks