First, I want to apologize to my readers for not being able to post lately, partly due to me being very busy these days;-)
As we all know, there are certain ways by which we can pass data to objects (of class). We can pass values during the time of construction as below:
class-name ob-name(values);
Or we may define a member function to accept data which can be called as below:
class-name ob-name;
ob-name.set(values);
Where set is the member function of the class.
But actually there is one more way to do so, yeah you guessed it right!, by overloading the parenthesis () operator.
Parenthesis () operator like other operators is overloaded with the following prototype:
ret-type operator()(arg1, arg2,...);
It is a unary operator hence the only argument passed to this function (implicitly) is this pointer. The argument list may contain any number of arguments as you wish to pass.
The following example program illustrates the overloading of parenthesis () operator in C++.
// Overloading Parenthesis ()
// Operator
#include <iostream.h>
class myclass
{
int a,b;
public:
myclass(){}
myclass(int,int);
myclass operator()(int,int);
void show();
};
// ------------------------
// --- MEMBER FUNCTIONS ---
myclass::myclass(int x, int y)
{
a=x;
b=y;
}
myclass myclass::operator()(int x, int y)
{
a=x;
b=y;
return *this;
}
void myclass::show()
{
cout<<a<<endl<<b<<endl;
}
// --- MEMBER FUNCTIONS ---
// ------------------------
void main()
{
myclass ob1(10,20);
myclass ob2;
ob1.show();
// it's a nice way to pass
// values, otherwise we
// would have to define and
// call a member/friend function
// to do so
ob2(100,200);
ob2.show();
}
Related Articles: