1

I came across the following program:

class Counter { 
 protected:         
  unsigned int count;  

 public:  
  Counter(): count(0) {}   
  Counter(int c): count(c) {}   
  unsigned int get_count() { return count; }  
  Counter operator++() { return Counter(++count); }  
};  

What does the last member function do (Counter(++count))?

snoofkin
  • 8,725
  • 14
  • 49
  • 86
AvinashK
  • 3,309
  • 8
  • 43
  • 94

2 Answers2

6

I think you wanted to implement operator++ for your class, and that should be implemented as:

Counter & operator++()
{
   ++count;
   return *this;
}

Now the question is what does it do? It does pre-increment. Now you can write ++counter and that will invoke the above operator overload, and which internally will increment the variable count by 1.

Example :

Counter counter(1);
++counter;
std::cout << counter.get_count() << std::endl;
++(++counter);
std::cout << counter.get_count() << std::endl;

Output:

2
4

What your original code does?

If you try to run the above code using your original implementation of operator++, it will print the following :

2
3

That is because you're creating another temporary object which you're returning, which when you write ++(++counter) the outer pre-increment will increment the temporary. So the outer pre-increment will not change the value of counter.count.

Even if you write ++(++(++(++counter))), its equivalent to just ++counter.

Compare the output here:

Note ++(++counter) does NOT invoke undefined behavior.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

The last function is an overloaded operator. Specifically in the prefix increment operator. It lets you use the prefix ++ operator on objects of that class. For example:

  Counter counter;
  ++counter;
  // note this is not implemented
  counter++;

This line

  Counter(++count)

constructs a new Counter object by first incrementing the current instances count then by using the constructor

   Counter(int c)

The result of the prefix increment, is therefore, a different instance (an incremented copy) then what prefix increment was called on.

Doug T.
  • 64,223
  • 27
  • 138
  • 202