I've overloaded the pre-increment operator using friend function. In the overloaded friend function, the value of the variable is showing correct. But that value is not shown in display function, why?
#include <iostream>
using namespace std;
class Rectangle {
public:
int breadth;
public:
void read();
void display();
friend void operator ++(Rectangle r1);
};
void Rectangle::read()
{
cout << "Enter the breadth of the Rectangle: ";
cin >> breadth;
}
void operator++(Rectangle r1)
{
++r1.breadth;
cout<<r1.breadth<<endl; //correct result
}
void Rectangle::display()
{
cout<<breadth<<endl; // not showing pre-incremented value, why ???
}
int main()
{
cout<<"Unary Operator using Friend Function \n";
Rectangle r1;
r1.read();
++r1;
cout << "\n breadth of Rectangle after increment: ";
r1.display();
return 0;
}
Your operator ++
takes the Rectangle
object by value, which means it receives a copy of its operand. It then dutifully increments the copy's breadth
member, prints it out, and then discards the copy when it's over.
You'll want to take the parameter by reference:
friend void operator ++(Rectangle &r1)
{
++r1.breadth;
}
Also note that it's quite common to overload unary operators using member functions instead of free functions. Used like that, you wouldn't have this problem:
class Rectangle
{
// ...
public:
void operator++ ()
{
++breadth;
}
// ...
};
A few side comments:
It's common for operator++
to return a reference to its operand, to mimic what built-in operators do. Just like it's possible to do ++ ++ i
for an int i
, it should be possible to do ++ ++ r
for a user-defined type r
as well.
In practice, operator overloading should only be used when a) you're writing a type which behaves similarly to a built-in type, or b) you're writing a domain-specific language. Incrementing a rectangle is not something I could intuitively explain, and would be best done as a named member function. How can you tell whether ++r
increases the breadth, or height, or both, or moves the rectangle to the right, or ...?