Foo Bar
Foo Bar

Reputation: 1892

Why can I access private data members through pointers and should I do this?

I just discovered that I can do this in C++, which compiles just fine (MinGW and VC++):

class A
{
private:
   void doSth();
   A* foo;
   A* bar;
};

void A::doSth()
{
  foo->bar;
}

The member field bar of foo is private. Why can I access it and should I do so?

Upvotes: 1

Views: 89

Answers (2)

vz0
vz0

Reputation: 32923

In C++, private means the access is limited to the same class, not to the same object instance.

Upvotes: 2

djechlin
djechlin

Reputation: 60768

You'll also notice that in A's methods, other instances of A's private variables may be access. Like

A::baz(A& other) {
    other.bar; // legal
}

Visibility is at the class level, not instance level.

Upvotes: 1

Related Questions