2
I am studying for the book Introduction to Object-Oriented Programming with C++ (Antonio Mendes da Silva Filho), and implemented an example of it as follows:
#include <iostream>
using namespace std;
class Contador{
    public:
        Contador(int c = 0){contador = c;};
        int getContador(){return contador;};
        Contador operator++(){
            ++contador;
            return contador; };
    private:
        unsigned int contador;
};
int main(){
    Contador c1, c2, c3;
    ++c1;
    ++c2;
    ++c2;
    ++c2;
    c3 = ++c2;
    cout << "c1: " << c1.getContador() << endl;
    cout << "c2: " << c2.getContador() << endl; 
    cout << "c3: " << c3.getContador() << endl; 
    return 0;
}
The counter return is only so that the assignment can be made on c3 = ++c2;
The program ran as expected, printing
c1 = 1
c2 = 4
c3 = 4
But in the answer of the book he adds an auxiliary variable in the following passage:
Contador operator++(){
            ++contador;
            Contador temp;
            temp.contador = contador;
            return temp; };
Compiling, the result is exactly the same. This auxiliary variable is unnecessary, right?
I kept reading and later he switched this part for
Contador operator++(){ 
 ++contador;
 return Contador(contador);
}– Leila
Which is probably a mistake too.
– Maniero
that
Contador(contador)is calling the builder?– Leila
Exactly, creates a new instance, but at the very least is not efficient.
– Maniero
About post-increment, I just implemented it like this:
Contador operator++(int){
 return contador;
 contador++;
 }– Leila
Its does not increase anything, because the increment occurs after the
return, never gets on that line. His is increasing before. He’s not making a mess not?– Maniero
Oops, I did, actually his is
return Contador(contador++);, I copied wrong.– Leila