I seem to have misinterpreted the life scope of objects in c++. If you'd consider the following:
class MyClass{
public:
int classValue;
MyClass(int value){
classValue = value;
}
static MyClass getMyClass(int value){
MyClass m1 = MyClass(value);
return m1;
}
};
int main() {
MyClass m1 = MyClass(3);
cout << m1.classValue << endl;
m1 = MyClass::getMyClass(4);
cout << m1.classValue << endl;
return 0;
}
This outputs:
3
4
And I thought, that when m1 gets a non-dynamic object, that has been created 'on the stack' of getMyClass function, me trying to get a value from it wouldn't work, because the object would be dead. Could someone enlighten me? Do not spare me any details!
And I thought, that when m1 gets a non-dynamic object, that has been created 'on the stack' of getMyClass function, me trying to get a value from it wouldn't work, because the object would be dead. Could someone enlighten me? Do not spare me any details!
There is a bit of misunderstanding.
Yes, the object is created on the stack in getMyClass
.
Yes, the object is dead when the function returns.
However, the line:
m1 = MyClass::getMyClass(4);
assigns the return value of the function to m1
before the object is dead. The object lives long enough to allow the run time to complete the assignment.
BTW, the line
MyClass m1;
is not right since MyClass
does not have a default constructor. You can replace the lines
MyClass m1;
m1.value = 3;
by just the one liner
MyClass m1(3);
Update
You need to change the constructor of MyClass
.
MyClass(int value){
value = value; // This does not initialize the
// member variable of the class.
// The argument shadows the member variable.
}
Use:
MyClass(int valueIn) : value(valueIn) {}