samedi 4 février 2023

When to use pointers or actual objects when going through member variables in c++ [closed]

so if I have 2 classes where class 1 has an instance of class two such as

class MyClass_1 {
public:

    

    

    void incrementNum() {
        secondClass.addOne();
    }

    void getTotalBannanas() {
        secondClass.getNumber();
    }



protected:
     
    myClass_2 secondClass;
    
};

class 2

class myClass_2 {
public:
    void addOne() {
        number += 1;
    }

    unsigned int getNumber() {
        return number;
    }

protected:
    unsigned int number = 0;

};

Now if I use the functions in class one to increment "number" then I print out the number I get what I would expect number goes up by the amount I incremented it by. But If I do the whole think through a middle class where I go through an object of class_C then go to myClass_2 then the whole the incremented amounts are no longer remembered.

By going through a middle class I mean by making changes like this

class MyClass_1 {
public:

    

    

    void incrementNum() {
        middle.getClass2().addOne();
    }

    void getTotalBannanas() {
        middle.getClass2().getNumber();
    }

protected 
middleClass middle;

middle class

class middleClass{
public:

myClass_2 getMyclass_2(){
return secondClass;
}

protected:

myClass_2 secondClass;

when I run the following code in main

int main() {
    myClass_1 woody;
    woody.incrementNum();
    woody.incrementNum();
    woody.getTotalBannanas();
    woody.incrementNum();
    woody.getTotalBannanas();

    return 0;
}

the first time I run this before the changes I get 2 and 3 After the changes I get 0,0

Could someone explain the reason why this extra step causes this. I know you can do this by using pointers such that the values are remembered but I am trying to understand the difference of using pointers and an actual instance of a class. Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire