Hi everyone I’m new to the forumn and programming – well iv’e read one book c++ programming in easy steps by Mike Mcgrath. I have now got a slightly more indepth book Sams teach yourself c++ in 24 hours fourth edition. All has been going well until I got upto hour 14 Operator overloading. I would be really grateful if someone could explain this concept in as simple terms as possible or help me try and understand the code bellow:
// Listing 14.2
// Overloading the increment operator
#include <iostream>
class Counter
{
public:
Counter();
~Counter(){}
int GetItsVal()const { return itsVal; }
void SetItsVal(int x) {itsVal = x; }
void Increment() { ++itsVal; }
const Counter& operator++ ();
private:
int itsVal;
};
Counter::Counter():
itsVal(0)
{}
const Counter& Counter::operator++()
{
++itsVal;
return *this;
}
int main()
{
Counter i;
std::cout << "The value of i is " << i.GetItsVal()
<< std::endl;
i.Increment();
std::cout << "The value of i is " << i.GetItsVal()
<< std::endl;
++i;
std::cout << "The value of i is " << i.GetItsVal()
<< std::endl;
Counter a = ++i;
std::cout << "The value of a: " << a.GetItsVal();
std::cout << " and i: " << i.GetItsVal() << std::endl;
return 0;
}
The value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i:3
I understand the code i.e default constructor/destructor, getter and setter access methods and the increment function etc even though the setter is never used. What confuses me most I think is the actual layout of the operator function as the book doesn’t explain that at all. The code bellow is what confuses me the declaration and definition:
const Counter& operator++ ();
const Counter& Counter::operator++()
{
++itsVal;
return *this;
what happens in the simplest terms when ++i is first called? Is i passed into the parameters of the operator function directly or a copy of it? Is itsVal its member variable then incremented and a reference of it returned by the this pointer? Why is the this pointer used? And what happens when i is assigned to a – the operator is called again and i is passed in? and itsVal is incremented and a reference of it returned? Lol god I’m confused.
Any help in explaing this or links to good pages that explain this in simple terms would be much appreciated. Many thanks jimbob.