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))?
2 Answers 2
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:
- http://www.ideone.com/xRXVq (your original code)
- http://www.ideone.com/xciWC (my code)
Note ++(++counter) does NOT invoke undefined behavior.
Comments
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.