Search code examples
c++pass-by-referenceprivate-members

C++ passing reference to class' private variable - compiler issue?


Is the passing by reference of a private variable in a class to be directly changed outside that class acceptable practice? Or is this something that the compiler 'should' pick up and prevent?

Example:

//-------------------------------------------
class Others
{
public:
 Others() {};
 void ChangeIt(string &str) { str = "Changed by Others"; }
};

//-------------------------------------------
class Locals
{
private:
 string PrivateString;
public:
 Locals() { PrivateString = "Set by Locals"; };
 void VisitOthers() { Others o; o.ChangeIt(PrivateString); }
 const string GetString() { return PrivateString; }
};

//-------------------------------------------
int main(void)
{
 Locals lo;
 cout << lo.GetString() << "\n";
 lo.VisitOthers();
 cout << lo.GetString() << "\n";
 return 0;
}

Output:

Set by Locals
Changed by Others

I need to do something like this using other/different objects, private to the owner class, but changeable by others when needed. Last thing I want is for this kind of practice to come back & byte me in the future.

What is essentially worrying me, is that I would like to view the class/struct as basically a pointer to a buffer, and the member's address as offsets into this buffer, so that even if you pass the pointer-value of a member it would be useless without the base-pointer of the class/struct to which it belongs. This is what I instinctively feel should be the case, so that the above example should not even be possible.


Solution

  • There is nothing to prevent, you pass your private member by reference. The function you are calling isn't accessing your private member, it is changing it's own argument (that happens to be the member of some class). The code is OK, but the important thing is that the function you called doesn't keep a reference to your private member.