Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access private elements of object of same class

Is this legal? If not, will the following code allow this?

class Foo
{
    friend class Foo;
}
like image 749
Xirdus Avatar asked Sep 30 '10 16:09

Xirdus


People also ask

Can objects of same class access private variables?

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.

Can a class access private members of the same class?

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.

Can we access private variable through object?

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.

Can object of a class access private methods?

Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.


2 Answers

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.

like image 162
JoshD Avatar answered Nov 12 '22 13:11

JoshD


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.

like image 28
Tyler McHenry Avatar answered Nov 12 '22 13:11

Tyler McHenry