In C++, I have a class A, and a class B.
In class A, there is a object (of class B) , I want to change the class A member data in the object of class B. How can I do that ?
I want to do this:
class A {
public:
A() {
new B(this);
}
private:
int i;
};
class B {
public:
B(A* parent) {
this->parent = parent;
}
change() {
parent->i = 5;
}
private:
A* parent;
};
Rather than setting B as a friend class to A, a better method to preserve encapsulation would be to add a setter method to class A.
Your class A would then look somewhat like this:
Then in your class B implementation, call set_i().
This way you’re not exposing and relying on private implementation details of class A in class B.