Search code examples
c++getterprivate-members

C++ Getting private value with getter


I have a class with private and public members I am trying to use a getter Get_Words() to access the private word member. This all compiles but when the value from dir[NORTH].Get_Words() = "NORTH"; Whenever the word was just a public function without the Get_Words() member function using dir[NORTh].word = "NORTH"; Why isn't the Get_Words assigning the value correctly to word?

class Words
{
  public:
    static void Set_Words();
    string Get_Words();
  private:
    string word;
}

string Word::Get_Words()
{
  return word;
}

...
dir[NORTH].Get_Word() = "NORTH";

and I also tried

dir[NORTH].Get_Word() = Set_Word( string "North");

I'm pretty sure I did the setter wrong but I am new to object oriented programming in c++ and can't figure out the best way to do this.


Solution

  • std::string Get_Word() returns by value, aka it makes a copy of the word and returns it. When you try to assign to it, you are trying to assign to a right hand reference, which is impossible.

    A way around this would to return a reference to word:

    std::string& Get_Word();
    

    But that is generally considered bad practice as the reference can outlive the class. A better way is to provide a setter along side the getter:

     void Set_Word(const std::string& w) {word=w;}
    

    or even better:

     template <typename T>
     void Set_Word(T&& w) {word=std::foreward<T>(w);}