trying to modify object in the class via get/set methods. I can't understand how change value just only use get/set method.
expected output : "Output : 89".
actual output : "Output : 0"
#include<iostream>
using namespace std;
class TestClass{
public:
int getValue() const{
return _value;
}
void setValue(int value) {
_value = value;
}
private:
int _value;
};
class A{
public:
TestClass getTestClass() const{
return _testClass;
}
void setTestClass(TestClass testClass) {
_testClass = testClass;
}
private:
TestClass _testClass;
};
int main()
{
A a;
a.getTestClass().setValue(89);
cout<<"Output :"<<a.getTestClass().getValue();
}
You're returning a copy of
_testClass
. So when you modify it withsetValue(89)
, nothing happens because you're only modifying a copy that is discarded at the end of the line. Instead, you should return a reference.Change this here:
To this:
And you get the expected output.
replace
with
You want to return a reference otherwise you are just returning a copy of the variable. But Keep in mind that returning a (non-const) reference to the member variables of a class is not a good design approach.
Some things:
please don't use
using namespace std;
- read here why.please don't name your variables
_testClass
- go withm_testClass
instead. You can read hear about the reasoning.