-1

I'm currently working on my first project using classes and objects, and I've run into a bit of a roadblock with my setter. I made up an example to illustrate the issue I'm running into (all one file for the sake of simplicity).

#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

class Example1
{
public:
    Example1() { name = "Mike"; }
    Example1(string aName) { name = aName; }
    string GetName() const { return name; }
    void SetName(string newName) { name = newName; }
private:
    string name;
};

class Example2
{
public:
    Example2() : anObj() {}
    Example2(string aName) : anObj(aName) {}
    Example1 GetObj() const { return anObj; }
    void SetObj(string objName) { anObj.SetName(objName); }
private:
    Example1 anObj;
};

int main()
{
    Example2 myObj;
    cout << myObj.GetObj().GetName() << endl;
    myObj.GetObj().SetName("Stan");
    cout << myObj.GetObj().GetName() << endl;
}

Output:

Mike 
Mike

The idea is to alter the member object in Example2 by using the member object's setter method, but the setter method doesn't seem to be working the way I expected.

I tried accessing the member by moving it to public (in Example2) and using dot notation, and that successfully changed the name. I'm not sure what the differentiation is, but, since the getter is working properly, I feel like something is wrong with how I'm using the setter.

The original problem I was trying to solve was having a Game class with a Player class member object. The idea is that the player could change their name if they wanted to.

Appreciate any help. Thanks.

Swordfish
  • 12,971
  • 3
  • 21
  • 43

1 Answers1

3

All your getters return a new object. Don't. Let them return a const &. But then you need a non const getter when you modify objects to call the setters:

const Example1& GetObj() const;
Example1& GetObj();

And now, the objects that are stored underneath will be updated, and not just their copies. Same for the strings.

You can also see the fact that the setters are not working on the proper objects by using a debugger.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62