2
votes

I am busy doing an assignment for a Comp Sci module in C++ and I am just a bit confused by one of the questions. It asks to give 3 implementations of an overloaded increment operator:

  1. Using the member function Adjust() which was coded in a previous question.
  2. Implementing the overloaded operator as a friend function.
  3. Implementing the overloaded operator as a member function.

Now I understand the concept of overloading the operators I think, that's okay. But I'm actually not too sure about the first one, using the existing member function Adjust(). Because surely if I'm overloading and just calling another function it will either be a friend or a member function calling another member function, if you know what I mean. Anyway, any help would be greatly appreciated. Below is my code for number 2 and 3 just for reference.

//Friend Function
friend Chequebook operator ++(const Chequebook &c); //Declaration in class.
Chequebook operator++(const Chequebook &c) //Function
{
    return Chequebook(c.Balance+100);
}

//Member Function
Chequebook operator++(); //Declaration in class.
Chequebook Chequebook::operator++() //Function.
{
    return Chequebook(Balance+100);
}

Sorry for the errors in the code. This is supposed to be a pre-increment operator overload.

3

3 Answers

2
votes

You probably misunderstand what increment operator does or you did not post full text of homework.

It modifies the object. It can be member and nonmember. It can be prefix and postfix. Here are the examples of how prefix (++x) increment is usually implemented:

class X 
{
  int i;
public:

  // member prefix ++x
  X& operator++() { ++i; return *this;}
};

class Y 
{ 
  int i;
public:
  void adjust() {++i;}
};

// non-member prefix ++y
Y& operator++(Y& y) { y.adjust(); return y;}

class Z 
{ 
  int i;
public:
  // friend prefix ++z
  friend Z& operator++(Z& z) { z.i++; return z;}
};

The postfix increment (x++) is different, should have additional int parameter.

2
votes

I interpret the first question as "implement the operator++ in terms of the member function Adjust which was coded previously".

Adjust is likely to be a public function so there's no need for a member implementation of operator++. You'd implement it as

Chequebook& operator++(Chequebook& i_lhs)
  {
  i_lhs.Adjust(1); // Or whatever Adjust actually takes as parameters.
  return i_lhs;
  }
0
votes

Well, your #2 attempt is clearly broken, because you have not actually changed the object at all and this is not the semantics of ++, either pre or post. In addition, you appear to be subtracting from the balance to increment?