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.