CodingMadeEasy
CodingMadeEasy

Reputation: 2337

Get and Set Function vs Referenced Functions

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

Answers (1)

Arne Mertz
Arne Mertz

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:

  1. You can only return a reference to an actual member of the object. If there is no such member, you are lost. Also, providing the reference means giving a hint on the implementation, thus leaking the abstraction the class should provide. It also makes changing the implementation hard. Consider a class 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.
  2. You will need a const and a nonconst version, so you have 2 methods against 2 methods - there are no savings in writing the reference version.
  3. You cannot apply boundary checks, e.g. phi has to be between 0 and 2*pi for polar coordinates. You cannot save yourself against e.g. p.phi() = 2500.4;
  4. You will always have a getter. Sometimes there are cases where only a setter is needed. It's not possible to have only setters with the reference version. And using a trivial setter method for setter-only members, but reference access for any other members would be inconsistent and confusing anyone reading your code.

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

Related Questions