Yes it is possible - you need to
return the variable by reference as well. Like this:
1 2 3 4 5 6 7 8
|
class Player {
public:
int& getDollars() { return dollars; }
int getDollars() const { return dollars; }
private:
int dollars;
};
|
You notice I provide two versions of the function - one for normal, and one for when you have a
const version of your object. I could have returned a const reference, but I may as well just copy it considering its only an
int.
As for if its bad practice: generally. Usually, the only thing that some outside of a class should know is its interface, what goes on underneath could change massively and it wouldn't care. In the case that you return a member variable, now everything knows that your
Player class has a 'dollars' member, might base some code around that fact, and if you decide to change it then you have a slight problem on your hands.
If you find that the variable itself IS an important part of the interface, though, you could either have a reference obtaining function like I demonstrated above or you could just make the variable public, actually putting it into your interface.