I am now teaching under graduate students C++ programming. I thought I will share the programs I have prepared so that it benefits everyone.
Overloading ++ Operator
In this post I have added sample programs overloading the ++ Operator. In C++ we have preincrement and postincrement operators. For example ++a is preincrement whereas a++ is postincrement. So in order to handle these two situations there should be two versions of the operator++( ) function. The two versions are shown below.
void operator++(int y); // for postincrement
// The call a++; will invoke this version
// The call a++; is same as the call a.operator++();
void operator++( ); // for preincrement
// The call ++a; will invoke this version
// The call ++a; is same as the call a.operator++(0);
Click here to download the C++ program.
void operator++(A, int); // for postincrement
Overloading ++ Operator with Friend Function
In C++ we can overload the ++ operator by using friend function. Here also we need two versions to manage the preincrement and postincrement versions of the ++ operator. The two versions are given below.
void operator++(A, int); // for postincrement
// The name of the Class is A
// The call a++; will invoke this version
// The call a++; is same as the call operator++(a);
void operator++(A); // for preincrement
//The name of the class is A
//The name of the class is A
// The call ++a; will invoke this version
No comments:
Post a Comment