Friday, November 18, 2011

How to Overload function call () operator in C++?

The argument list of function call operator () is evaluated and checked as according to the argument passing rules. The function call operator is a binary operator with object as one operand and argument list as other operand. In the following statement:
obj(arg_list);



here obj can be interpreted as left hand operand and arg_list as right hand operand. The function call operator () is useful in class which have only one operation or one operation which is frequently used. The function call operator ( ) is also called application operator. Because of function call operator the objects behave like functions syntactically. The object of the class that defines the function call operator is called function object because the object behave like functions. The example program is given below for function call operator overloading:
#include<iostream>
#include<cstdlib>
using namespace std;

class Complex{
    private:
        float real;
        float imag;
    public:
        Complex():real(0),imag(0){}
        Complex operator ()(float re, float im){
            real+=re;
            imag+=im;
            return *this;
        }
        Complex operator() (float re){
            real+=re;
            return *this;
        }
        void display(){
            cout<<"("<<real<<","<<imag<<")"<<endl;
        }
};

int main(){
    Complex c1, c2;
    c2 = c1(3.2,5.3);
    c1(6.5,2.7);
    c2(1.9);
    cout<<"c2=";c1.display();
    cout<<"c2=";c2.display();
    return 0;
}


No comments:

Post a Comment