Reputation: 2337
I have this code:
#include<iostream>
#include<string>
class Test
{
public:
std::string& GetText()
{
return text;
}
void Display() { std::cout << text << std::endl; }
private:
std::string text;
};
int main()
{
Test test;
test.GetText() = "Testing";
test.Display();
}
now this referenced function works like a get and setter under 1 function name. So I wanted to know is it beneficial to use this method or would it be more beneficial to use a separate get and set method. Or would it just make more sense to make the variable public.
Upvotes: 0
Views: 176
Reputation: 24596
There is no difference (or at least not much) in terms of performance, behavior etc. between the two versions. But there are other things to keep in mind for the reference version:
Point
, implemented with x and y coordinates. You won't be able to provide a referenced access to the polar representation of a point, nor will you be able to easily change the implementation to polar coordinates, because after that the reference getX()
and getY()
accessors would not work any more.phi
has to be between 0
and 2*pi
for polar coordinates. You cannot save yourself against e.g. p.phi() = 2500.4;
So while there are some cases, where the referenced access is useful, you should use classic getter and setter methods most of the time.
Upvotes: 1