I know that the implementation of properties-like objects has been discussed many times, but what I need is slightly different from the various solutions proposed.
I want an object that has the same semantics of a variable, but when its value changes, I want to perform some action. This means that there are implicit get / set methods that are implemented when the = operator and the implicit conversion operator are overloaded.
Note that when I mean property-like, I do not mean necessarily semantic object.property, but simply a way to have implicit get / set methods (as in property-like-variable = value). The reason is because I have some existing code that uses the variable, I want to perform some action every time the value of the variable changes without changing the existing code (only the declaration of the variable should change).
I got this result with a minimal code like this:
#include <stdio.h>
class Int
{
int _value;
public:
Int() { printf("Int: initial value undefined\n"); }
Int(int value) : _value(value) { printf("Int: initial value is %d\n", _value); }
operator const int() const { return _value; }
int operator=(int value)
{
_value = value;
printf("new value is %d\n", value);
return value;
}
};
This is a usage example:
class C
{
Int _i;
public:
C() : _i(2) { }
void foo()
{
_i = 3;
printf("foo(): _i = %d\n", _i);
}
};
int main()
{
int i;
Int I;
i = 1;
I = i;
I = I + 1;
C c;
c.foo();
}
Now a few questions:
- Is this specific need already discussed? Have a design template?
- Am I doing something bad here? (both in terms of implementation and in terms of design).
- Is there any performance flaw with this, or is the compiler able to optimize it without overhead?
- ? "" ( "" ).
- ? , - / .