jmasterx jmasterx - 3 months ago 9
C++ Question

Can a private variable be accessed through it's pointer?

Would it be possible for a public function to return a pointer to a private variable in the class. If so / if not, what would happen? would it crash or is there anything highly unsafe about this? Can the pointed data be read or written to?
Thanks

Answer

Yes, a member function may return a pointer (or reference) to a private data member. There is nothing wrong with this except that in most circumstances it breaks encapsulation.

The data member can certainly be read via the returned pointer or reference. Whether or not it can be written to depends on whether the returned pointer or reference is to a const-qualified object (i.e., if you return a const T*, you won't be able to modify the pointed-to T). For example:

class Example
{
public:
    int*       get()             { return &i; }
    const int* get_const() const { return &i; }
private:
    int i;
};

int main()
{
    Example e;

    int* p = e.get();
    int a = *p;    // yes, we can read the data via the pointer
    *p = 42;       // yes, we can modify the data via the pointer

    const int* cp = e.get_const();
    int b = *cp;   // yes, we can read the data via the pointer
    *cp = 42;      // error:  pointer is to a const int         
}