Change class attributes passed as parameter to another class

Asked

Viewed 74 times

0

There are two classes, classa and classb, where it is passed as a parameter to the classb an instance of classa and subsequently an attempt is made to change a parameter of the classa through the classb, but without success, why doesn’t it work?

Test code:

#include <iostream>

class CLASSA
{
public:
    int attribute = 10;

    void change(int a) {
        this->attribute = a;
    }
};

class CLASSB
{
public:
    CLASSA *otherclass;

    CLASSB(CLASSA classa) {
        this->otherclass = &classa;
    }

    void changeotherclass() {
        this->otherclass->change(2);
    }
};

CLASSA  classa;
CLASSB  classb(classa);

int main(int argc, const char * argv[]) {
    classb.changeotherclass();

    std::cout << classa.attribute;

    return 0;
}

1 answer

1


In C++ the arguments are, by default, passed by value, i.e., the function that receives the argument has access to a copy of the variable and not the variable itself. The copy of the variable is destroyed at the end of the function execution. This means that when you do:

CLASSB(CLASSA classa) {
    this->otherclass = &classa;
}

The pointer otherclass points to a temporary variable that will be destroyed at the end of constructor execution. And as a consequence, the method

void changeotherclass() {
    this->otherclass->change(2);
}

writes in an area of mémoria that belonged to an object that has already been destroyed (this if I’m not mistaken results in undefined behavior).

The solution would be to take the address of the object. For example, in CLASSB:

CLASSB(CLASSA* classa) {
   this->otherclass = classa;
}

And pass the address as argument:

CLASSB  classb(&classa);

It is recommended to always initialize a pointer.

CLASSA *otherclass = nullptr;
  • Very grateful. Why this recommendation? What is the risk of not initializing pointers?

  • 1

    Simple: you would not be able to check if pointer is invalid because it would be initialized with a random address. You have [a question here that speaks of the same subject] (https://answall.com/questions/304535/por-que-attributr-null-em-um-ponteiro-depois-de-um-free). NULL and not nullptr, but they’re almost the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.