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;
}
Very grateful. Why this recommendation? What is the risk of not initializing pointers?
– Vinícius Lara
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 notnullptr
, but they’re almost the same.– user72726