Reputation: 2733
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;
};
Upvotes: 1
Views: 154
Reputation: 21363
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:
class A {
public:
A() {
new B(this);
}
void set_i(int value)
{
i = value;
}
private:
int i;
};
Then in your class B implementation, call set_i().
class B {
public:
B(A* parent) {
this->parent = parent;
}
change() {
parent->set_i(5);
}
private:
A* parent;
};
This way you're not exposing and relying on private implementation details of class A in class B.
Upvotes: 2
Reputation: 109547
class A {
friend class B;
private:
int i;
public:
A() : i(0) {
new B(this);
}
};
Upvotes: 2
Reputation: 3965
In declaration of class A
you need to define class B
as a friend:
friend class B;
Upvotes: 3