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

Recommended Answers

All 2 Replies

Look at the way operator++ is defined in your code at line 8; it has no class name before the method name. It is not a member of the class point but rather just a function, the only difference being it has been declared as a friend of point so that it can access the private data members of point.

Since it is a function not a method on the class you have to pass the point you are changing into the function by reference or you will get and change a temporary copy rather than the class you called the operator on.

Personally I might well make operator++ a method rather than a friend function and if I did the code would look like, I would also make it return a const ref rather than a value to help reduce copying (an issue for large classes)

class point 
{
  int a,b;
public:
  point(){};
  point(int Ia, int Ib) {a=Ia; b=Ib;}
  const point& operator++(point &p1);
};

const point& point::operator++() {
  this->a++; 
  this->b++;
  return p1;
}

However once you get to implementing binary operators, like operator+ you might well want to implement the operators as friend functions so you can implement them with the parameters both ways round i.e. point operator+(const point& p, int i); and point operator+(int i, const point& p);

Hi thanks!
I understand it better now.
-FH

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.