In the code snippet, I am able to access the private member variable outside the class scope. Though this should never be done, why is it allowed in this case? Is it a bad pract
This code:
int& methodTwo() { return x; }
Means that the function returns a reference to an integer. Just like when passing a value by reference to a function, if the return value of methodTwo
gets changed, so does the value that methodTwo
returned. In this case, class field x
.
In the code you have written, this means that you are letting the private variable x
escape its scope (a class field) and be passed around in the outside world. This certainly is a bad practice (because x
can be changed in ways that may break class foo
, but it is certainly allowable.
Remember public/private/protected are compile-time only. Once your application gets compiled, private fields sit next to public fields and there is no protection against modification. The same is true for managed languages like C# and Java.
You should generally avoid returning references because it makes it crazy-hard to understand when constructors/destructors get called. However, returning a reference can be faster. If your method returned a struct type that was HUGE, returning a const reference to that same struct type should only take four-to-eight-bytes (a pointer to that object). However, there are better ways to optimize for this sort of thing.