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,91514 gold badges52 silver badges89 bronze badges
asked Apr 26, 2011 at 17:17

2 Answers 2

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.

answered Apr 26, 2011 at 17:21
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Apr 26, 2011 at 17:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.