Search code examples
c++classprivateencapsulationdata-members

How to access private data members outside the class without making "friend"s?


I have a class A as mentioned below:-

class A{
     int iData;
};

I neither want to create member function nor inherit the above class A nor change the specifier of iData.

My doubts:-

  • How to access iData of an object say obj1 which is an instance of class A?
  • How to change or manipulate the iData of an object obj1?

Note: Don't use friend.


Solution

  • You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.

    (You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)