Think of the ++ operator as just another method of the class, like getItsVal() and setItsVal(). Instead of ++ another method of incrementItsVal() could have been written like this:
const Counter& Counter::incrementItsVal()
{
++itsVal;
return *this;
}
and used like this:
Counter i;
i.setItsVal(1);
i.incrementItsVal();
In theis case using the ++ operator is equivalent to, behaves the same way as, and is shorthand for incrementItsVal(). Which would you rather type:
++i;
or
i.incrementItsVal();
They mean the same thing.
>>Is itsVal its member variable then incremented and a reference of it returned by the this pointer?
Yes.
>>Why is the this pointer used?
Because this points to the address of i in this case, and in general, this points to the current object. In this case Counter is quite simple, and could have been replaced by a simple int variable. However, for teaching purposes, simple classes like this are frequently used. There will come a time when not so simple classes are used and the same approach can be used.
>>And what happens when i is assigned to a – the operator is called again and i is passed in?
All objects need a default constructor, a copy constructor, an assignment operator, and a destructor. If you don't explicitly create one, the compiler will do it for you. The compilers version of the assignment operator and the copy constructor will probably be a simple assignment of member variables from one object to another. This is often adequate, but not always, particularly if pointers are used as data members. In this case there is not copy constructor or assignment operator so a default version is made by the compiler.
In this line:
Counter a = ++i;
the = sign is really a placeholder and not an assignment operator. This line means increment the itsValue of i first, then return a reference to i, probably in the form of a temporary object. The temporary object is then used as the argument for the copy constructor which is used to create the Counter object called a. The itsValue of a will be the same as the itsValue of i. In essence, this line could be rewritten like this:
Counter a(++i);
but again, for readability purposes
Counter a = ++i;
is probably easier, so that's whats done.
Last edited by Lerner; Oct 30th, 2006 at 11:14 am.
Reputation Points: 718
Solved Threads: 373
Nearly a Posting Maven
Offline 2,253 posts
since Jul 2005