Is there a function in c++ that when a variable got changed it automaticly call a function?
In one word; no.
But what you should do is wrap the variable into a class (i'm not going to suggest operator overloading), and change it via a set(...) function. Then you simply call the function from the set function.
No, you should encapsulate the variable in a couple of get/set methods.
You could make the variable private to some class and then use member functions for the change in the first place.
You could put your extra code into the member function itself, or you can have that code separate and have the member function call it on change.
Is there a function in c++ that when a variable got changed it automatically call a function?
No, not that I could think of. You can, however, wrap access to the variable in a suitable wrapper which allows you to hook into assignment.
Something like this:
//Beware, brain-compiled code ahead!
template<typename T>
class assignment_hook {
public:
typedef void (hook_t)(const T& old_value, const T& new_value);
assignment_hook(T& value, hook_t hook) : ref_(value), hook_(hook) {}
T& operator=(const T& rhs)
{
hook_(ref_,rhs);
ref_ = rhs;
}
private:
// I'd rather not want to think about copying this
assignment_hook(const assignment_hook&);
void operator=(const assignment_hook&);
T& ref_;
hook_t hook_;
};
As Noah noted in a comment,
typedef boost::function<void(const T&,const T&)> hook_t;
(or, if your compiler has it, std::tr1::function
or std::function
) would greatly improve on that, because it allows all kinds of "compatible" functions to be called. (For example, it enables all kinds of magic using boost/std::/tr1::bind<>
to call member functions and whatnot.)
Also note that, as adf88 said in his comments, this just does what was asked for (monitor write access to a variable) and is by no means a full-fledged property implementation. In fact, despite C++' attitude to implement as much as possible in libraries and as little as possible in the language, and despite the attempts of many people (some of them rather smart ones), nobody has found a way to implement properties in C++ as a library, without support from the language.
Depending on the complexity of your program, you could use Listeners that monitor certain objects for state changes, and have other parts of your program subscribe for events from that listener.
However, the best option would be to put this functionality into the setter method for that variable. It could be listener functionality, or a direct function call.
You can encapsulate that variable, and have listeners that are notified when the value changes. I'd go with boost::signals or boost::signals2 for that :
http://www.boost.org/doc/libs/1_43_0/doc/html/signals2.html
and here's some info on the observer pattern : http://en.wikipedia.org/wiki/Observer_pattern
If the variable has a class type, you can overload its operator =()
function. You cannot do this if the variable is a primitive type.