22
loading...
This website collects cookies to deliver better user experience
()
operator' as Functors or simply 'using objects as functions' . If you don't know what operator overloading is, don't worry we will go through it. If you already know what operator overloading is, skip to Functors .int a=5,b=3,c=a+b;
myObject objA(10);
myObject objB(20);
myObject objC=objA+objB;
return_type operator op(parameters){
statements;
....
}
op
can be any operator you wish to overload. Example +
,-
,*
etc., there are few exceptions for operators that can be overloaded.These are few operators which you cannot overload. .
Member access or dot operator,? :
Ternary or conditional operator,::
Scope resolution operator,.*
Pointer to member operator,sizeof
The object size operator,typeid
Object type operator.
+
operator overloading along with some additional code.class myObject{
private:
int _value;
public:
myObject(){}
myObject(int a){
_value=a;
}
// +(plus) operator overloading
myObject operator +(myObject obj){
myObject temp;
temp._value=_value+obj._value;
return temp;
}
// function to print present value
void print(){
cout<<"value: "<<_value<<endl;
}
};
int main(){
myObject objA(10);
myObject objB(20);
myObject objC=objA+objB; //3rd line in main function
objC.print(); //prints : value: 30
}
+
operator, then once after detecting it sends objB as a parameter to objA's operator overloading function. Here in the function it creates a temporary temp
object of same class and assigns value by adding values of both current object value_value
and value in objB by obj._value
.It then returns this temp object, this returned object is assigned to objC. This is how objC gets its value.objC.print()
function we get output as value: 30
which indicates _value variable in objC is being assgined.myObject obj(10);
cout<<obj(2); //this will output 20, here you are trying to multiply obj value by 2
obj
is acting like function, this is achieved by the concept Functors. Here this function mutiplies the value of object obj 10
by given parameter value 2
and returns the multiplied value 20
.()
operator. Below is the class definition that implements this operator overloading.class myObject{
private:
int _value;
public:
myObject(){}
myObject(int a){
_value=a;
}
int operator ()(int value){
return _value*value;
}
};
_value
multiplied by passed parameter. Complete code of above implementation :#include <iostream>
using namespace std;
class myObject{
private:
int _value;
public:
myObject(){}
myObject(int a){
_value=a;
}
int operator ()(int value){
return _value*value;
}
};
int main(){
myObject obj(10);
cout<<obj(4); //prints : 40
}
obj
.I could create another object with another state value and I can apply any changes to the value. Here I am applying changes to the state of an object not an hardcoded value, this is where functors are useful.FUNCTORS ARE THE OBJECTS WHICH COULD BE USED LIKE A FUNCTION