Most of time we used classes and sorts the collection of objects on different member variables. In these scenarios we have to write different-different Functor with respect to the classes. The following code provides a generic Functor which can be used with any class and can be used easily.

Let see an example. class A have a default, parametrized , copy constructor and assignment operator.

class A

{

public:

A (){

cout << “default constructor A()” <<endl;

}

A (int i): x(i) {

cout << “A(): ” << x <<endl;

}

A (const A &obj) {

x = obj.x;

cout << “Copy constructor A(): ” << x <<endl;

}

A& operator = (const A &obj) {

cout << “A operator = ” <<endl;

x = obj.x;

return *this;

}

int x ;

};

Lets create a class which have A and don’t initialize it in initialization list:

class Test {

public:

Test(A &a1) {

a1 = a;

cout << “Test: ” << endl;

}

A a;

};

int main()

{

A a(9);

Test obj(a);

return 0;

}

The output is:

A(): 9 default constructor A() A operator = Test:

———————————————————————————————————————————————–

Now do it in initialization list:

class Test {

public:

Test(A &a1):a(a1) {

cout << “Test: ” << endl;

}

A a;

};

Output is:

A(): 9 Copy constructor A(): 9 Test:

In the initialization list, object initialize itself in list while in other, constructor is called and then assignment operator over it. Now assume if a class have many member variables including STL container etc then there would big overhead while creation and in assignment operator.

Inline is also behaving the same way but it’s a request to the compiler. Therefore, it not sure whether it work as pre processor or not. If function has big loops/switch/recursion then compiler ignores the request and treat it as normal function.