What are the different ways to access/initialize a private member of a class?

Are functions and constructors really the only way to access private members in a class? also, how useful can private members be? do they have their uses in high level programming?
There's another way which is a kind of hack. But you need a functions to tell you the offset of the variable inside the object. Then you can use the offset of the variable to access the data using the objects pointer.
One point of object orientated programming is encapsulation, which hides internal data. Usually the private members are used to maintain internal state of the objects, and author of the class assumes you won't be interested in the internal of the class.
Hi,

Are you aware of initialiser lists in constructors? Google them if not.

As liuyang alluded private members are almost essential.

Imagine an Arc class that has a constructor which takes 3 points on the arc, from which all of the other variables should be calculated. To do this, one needs to bisect the 2 segments to calc the centre point. So there should be a bunch of private functions with their own local and or private class variables. One shouldn't make them public, as they shouldn't concern the client.

@Joshhua5

I heard awhile back that any kind of subversion involving pointers to access class member is not allowed, but am not sure about the details.
Hacking into the class is possible.

Say we have a class:

1
2
3
4
5
6
7
8
class A
{
public:
  A();
private:
  int dataA;
  int dataB;
};


You can make a identical struct

1
2
3
4
5
struct HackA
{
  int dataA;
  int dataB;
};


You can use it like this:

1
2
3
// A something;
HackA *hack = (HackA*)&something;
hack->dataA = whatever;


However it's another story if virtual methods and inheritances are introduced...
Hi,

Also I have a vague idea that the order the variables are stored in memory is not set in stone, it might be UB if one tries it.

And, about subversion - what is the point of having a whole lot of rules defined in the standard - if it is possible to subvert them? Especially such a basic and inherent thing such as private members.
Topic archived. No new replies allowed.