Currently writing a program for an OOP course on encapsulation. The program is required to instantiate only one object in main, but then instantiate multiple objects, within the first object, to perform calculations on arrays (Values
)held within each object.
I have been taught that I should ensure that objects are responsible for performing calculations on their own data. But..
I am currently using an approach of overloading the subscript operator, in order to perform the add()
function and assign the result equal to obj1
of class foo
.
My question is: As obj1
is a member of class foo
and the function add()
is a member of class bar
is this breaking the encapsulation rule of modifying another objects private members? Even if that object, obj1
is a private member of the class bar
?
class foo
{
public:
foo(double* = 0, unsigned long = 0, bool = false);
~foo();
double& operator[] (unsigned int Index) { return Values[Index]; }
const double& operator[] (unsigned int Index) const { return Values[Index]; }
private:
double* Values;
};
class bar
{
public:
bar(double* = 0);
~bar();
void add();
private:
double* Values;
foo obj1;
foo obj2;
};
void bar::add()
{
obj1[1] = obj2[1] * Values[1];
}
int main()
{
bar obj3;
obj3.add;
}