C++ Using Setter of a member object





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-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.










share|improve this question

























  • Grab your C++ book of choice and read the chapter about "return by reference" / "return by value".

    – zett42
    Nov 24 '18 at 0:11











  • Handy reading: What's the difference between passing by reference vs. passing by value?

    – user4581301
    Nov 24 '18 at 0:12











  • See how much easier your code is to read with 3 minutes of formatting?

    – Lightness Races in Orbit
    Nov 24 '18 at 0:17











  • Why do you use the initialization-list for Example2::anObj but not for Example1::name?

    – Swordfish
    Nov 24 '18 at 0:17











  • @LightnessRacesinOrbit it was 4.2 minutes.

    – Swordfish
    Nov 24 '18 at 0:17


















-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.










share|improve this question

























  • Grab your C++ book of choice and read the chapter about "return by reference" / "return by value".

    – zett42
    Nov 24 '18 at 0:11











  • Handy reading: What's the difference between passing by reference vs. passing by value?

    – user4581301
    Nov 24 '18 at 0:12











  • See how much easier your code is to read with 3 minutes of formatting?

    – Lightness Races in Orbit
    Nov 24 '18 at 0:17











  • Why do you use the initialization-list for Example2::anObj but not for Example1::name?

    – Swordfish
    Nov 24 '18 at 0:17











  • @LightnessRacesinOrbit it was 4.2 minutes.

    – Swordfish
    Nov 24 '18 at 0:17














-1












-1








-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.










share|improve this question
















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.







c++ class setter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 0:16









Swordfish

10.2k11437




10.2k11437










asked Nov 24 '18 at 0:03









Mike SchultzMike Schultz

112




112













  • Grab your C++ book of choice and read the chapter about "return by reference" / "return by value".

    – zett42
    Nov 24 '18 at 0:11











  • Handy reading: What's the difference between passing by reference vs. passing by value?

    – user4581301
    Nov 24 '18 at 0:12











  • See how much easier your code is to read with 3 minutes of formatting?

    – Lightness Races in Orbit
    Nov 24 '18 at 0:17











  • Why do you use the initialization-list for Example2::anObj but not for Example1::name?

    – Swordfish
    Nov 24 '18 at 0:17











  • @LightnessRacesinOrbit it was 4.2 minutes.

    – Swordfish
    Nov 24 '18 at 0:17



















  • Grab your C++ book of choice and read the chapter about "return by reference" / "return by value".

    – zett42
    Nov 24 '18 at 0:11











  • Handy reading: What's the difference between passing by reference vs. passing by value?

    – user4581301
    Nov 24 '18 at 0:12











  • See how much easier your code is to read with 3 minutes of formatting?

    – Lightness Races in Orbit
    Nov 24 '18 at 0:17











  • Why do you use the initialization-list for Example2::anObj but not for Example1::name?

    – Swordfish
    Nov 24 '18 at 0:17











  • @LightnessRacesinOrbit it was 4.2 minutes.

    – Swordfish
    Nov 24 '18 at 0:17

















Grab your C++ book of choice and read the chapter about "return by reference" / "return by value".

– zett42
Nov 24 '18 at 0:11





Grab your C++ book of choice and read the chapter about "return by reference" / "return by value".

– zett42
Nov 24 '18 at 0:11













Handy reading: What's the difference between passing by reference vs. passing by value?

– user4581301
Nov 24 '18 at 0:12





Handy reading: What's the difference between passing by reference vs. passing by value?

– user4581301
Nov 24 '18 at 0:12













See how much easier your code is to read with 3 minutes of formatting?

– Lightness Races in Orbit
Nov 24 '18 at 0:17





See how much easier your code is to read with 3 minutes of formatting?

– Lightness Races in Orbit
Nov 24 '18 at 0:17













Why do you use the initialization-list for Example2::anObj but not for Example1::name?

– Swordfish
Nov 24 '18 at 0:17





Why do you use the initialization-list for Example2::anObj but not for Example1::name?

– Swordfish
Nov 24 '18 at 0:17













@LightnessRacesinOrbit it was 4.2 minutes.

– Swordfish
Nov 24 '18 at 0:17





@LightnessRacesinOrbit it was 4.2 minutes.

– Swordfish
Nov 24 '18 at 0:17












1 Answer
1






active

oldest

votes


















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.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454063%2fc-using-setter-of-a-member-object%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.






    share|improve this answer




























      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.






      share|improve this answer


























        3












        3








        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 0:06









        Matthieu BrucherMatthieu Brucher

        17.7k52445




        17.7k52445
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454063%2fc-using-setter-of-a-member-object%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini