Is this legal? If not, will the following code allow this?
class Foo
{
friend class Foo;
}
Can one object access a private variable of another object of the same class? Private means "private to the class", NOT "private to the object". So two objects of the same class could access each other's private data.
You can access private members from any code block that is defined in the same class. It doesn't matter what the instance is, or even if there is any instance (the code block is in a static context). But you cannot access them from code that is defined in a different class.
We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself.
Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.
That's redundant. Foo already has access to all Foo members. Two Foo objects can access each other's members.
class Foo {
public:
int touchOtherParts(const Foo &foo) {return foo.privateparts;}
private:
int privateparts;
};
Foo a,b;
b.touchOtherParts(a);
The above code will work just fine. B will access a's private data member.
Yes it is legal for an object of class Foo
to access the private members of another object of class Foo
. This is frequently necessary for things like copy construction and assignment, and no special friend declaration is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With