Hi guys,
I'm learning C++ from a book and I have a question about defining unary operators: In the book I'm working with there's an example, where they define a class called point, and define ++ operator for point as friend. here's the example:
class point {
int a,b;
public:
point(){};
point(int Ia, int Ib) {a=Ia; b=Ib;}
friend point operator++(point &p1);
};
point operator++(point &p1) {
p1.a++; p1.b++;
return p1;
}
The book goes on to state that when doing this we must send the object by reference, or else the function will not change the original value. Instead it would create a copy of the object, and change only the copy. I did not quite understand why that would happen. Why do I even need to declare parameters in point operator++(point &p1)
?
Why can't I simply define the operator like so:
point operator++() {
this.a++; this.b++;
return *this;
}
Doesn't ++ operators implicitly know the object that called them? Does having the operator defined as friend affects that?
Thanks a bunch,
-FH