virtual op( ) overloading to replace setter method

template class Property{
Value val;

virtual void operator() (const Value& val);
}

* Note this is not a const method; it actually changes host object state
* it’s like a setter method, setting the this->val field
* but it uses op overloading instead of a setter method.

Q: If you have a template instance Volatility as Property<string,
double>, and then create an object myVol, how do you set its value to
1.2 ?
A: using regular setter setValue(), you would call
myVol.setValue(1.2), but using the ( ), it’s

myVol(1.2)

There’s also a “getter” method.
* note the const
* note the double parenthesis.

{…
virtual Value operator ( ) ( ) const; // note the double parenthesis.

}

The technique to overload q[ ( ) ] is a throwback to the constructor
initializer syntax

ConstructorName() :
field1(val5),
field2(val0)
{}

Big difference now is what identifier you put in front of the paren –
put the variable name rather than the field name.

Note overloading q[ ( ) ] is the basis of many advanced techniques including STL functors, custom function objects and probably Boost bind. This overloading is needed for function-like syntax.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s