Hello, I recently started learning C++ using the 'teach yourself in 21 days' tutorials, and I have hit a little snag in my understanding. I've been ignoring it for the time being in hope that it will click later on but upon reaching the operator overloading section I feel I need to understand this now.
Here is some code of what I am working on...
There is nothing wrong with the code, but there is one thing I cannot get to grips with and that is a member function(or any other function for that matter) returning an object.Code:#include <iostream> using namespace std; typedef unsigned short int USHORT; class Counter { public: Counter(); ~Counter() {} USHORT GetItsVal() const {return itsVal;} void SetItsVal(USHORT x) {itsVal = x;} const Counter& operator ++ (); private: USHORT itsVal; }; Counter::Counter(): itsVal(0) {}; const Counter& Counter::operator ++ () { ++itsVal; return *this; } int main() { Counter i; cout << "The value of i is " << i.GetItsVal() << endl; ++i; cout << "The value of i is " << i.GetItsVal() << endl; Counter a = ++i; cout << "The value of a is " << a.GetItsVal() << endl; cout << "The value of i is " << i.GetItsVal() << endl; ++a; cout << "The value of a is " << a.GetItsVal() << endl; cout << "The value of i is " << i.GetItsVal() << endl; return 0; }
This example is prevelant due to the overloaded prefix operator function returning a reference to a Counter object, specifically the dereferenced 'this' pointer.
I can understand a return value being an integer, but I'm having trouble understanding an entire object being returned, especially when a member function returns a different object, I am unsure of how to use them.
Like I said I have ignored this until now. In the example a counter is created (i) and using the overloaded prefix function, somehow a reference to a counter is returned, the 'this' pointer points to the calling object so there is a reference to 'i' itself returned but where does it go? it is not used, I am confused.
Secondly when creating the counter 'a', it is said to equal ++i. Now I am really confused. The ++ increments 'i' and then returns itself as being equal to 'a', so 'a' is a copy of 'i'... this is confusing enough but if the return value is a reference also, is 'a' now not a reference to 'i'? This is obviously not the case but thats as far as I can get at my point of understanding.
Could somebody please clarify this for me.