Problem: when write type cast operator for object, i want to change state of object’s field, who calls cast-operation.
Question: how can i change state of field in object, which one call cast operator?
Example below:
#include <iostream>
class myClass {
public:
int field;
int res;
myClass() { field = 0; res = -1; }
operator bool() {
field = 0;
return static_cast<bool>(res);
}
myClass operator>(int val) {
if (field > val) {
res = 1;
}
else {
res = 0;
}
return *this;
}
};
int main() {
myClass example;
example.field = 10;
bool conRes = static_cast<bool>(example > 5);
return 0;
}
But field doesn’t change, cause in cast operator will sending copy of object:
test add before cast: 0000000A7BAFF6C8
test add bool() cast: 0000000A7BAFF7C4
test add after cast: 0000000A7BAFF6C8
>Solution :
I believe the problem is in the return type you have chosen for operator >. You are returning a new instance of myClass. If you would like the result to act as the original class, you should return a reference to it instead. This is done by changing the return type to include &.
myClass operator>(int val)
return *this; // return a copy of this object
myClass& operator>(int val)
return *this; // return a reference to this object
In your code, with this change the reference myClass& returned will give direct access to example and you should see that field will be set to 0 during the cast operator call.
If you are familiar with objects in other programming languages C++ may be different in this way. myClass is a new object, but there are two ways to gain access to the object from another name alias.
myClass&is a reference, which simply becomes another name for amyClassthat existed before it.myClass*is a pointer, which may also access an existingmyClass. However, unlike a reference, the pointer can be reassigned, and changed to point at a differentmyClass.
So, references are used when you need an alias to access one specific object. Pointers are used when you want to access different objects over time. A pointer that is never reassigned is similar in capability to a reference.