For some reason I don't remember the tutorial ever discussing what a return type a& is. The tutorial certainly has discussed that return type a* would be a pointer to an object of class/type a. Therefore does a& mean a the value pointed to by a pointer? In fact the function is returning the dereferenced "this" which would seem to be consistent with what I think a& means. And if this is the case, I don't think I understand what is actually being returned if the pointer is pointing to an object of a class. In this example the class has the form
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
}
and so how can this entire class be passed as a value? Thanks for your help.
CVector& is a reference to class CVector this is a pointing to the class object whose + operator was calling
so *this is that object itself
Returning CVector would create a copy of it, returning CVector& would return the exact object
You are passing by value a CVector object (not the entire class).
Usually we prefer CVector operator + (const CVector&); so the compiler can just use the object itself.
OK thanks for all that. I guess there is a lot more here than meets the eye; would be nice if the tutorial discussed all this instead of leaving the individual confused. Anyway, let me see if I have it nailed.
Let us say sometype is some type. To declare X as being of type sometype we say
sometype X;
To declare X as a pointer to an object of sometype we say
sometype* X;
If X is an argument to a function and we wish to declare it as a pointer to an object of sometype then we declare it as
void function name (sometype& X);
If we wish to declare that a function returns a pointer to an object of type sometype then we say
sometype* function name (arguments);
If we wish our function to return an object of type sometype, but we wish it to return the original object that came into existence during the running of the function, and hence not have it disappear as would normally be the case of a local object, then we have to declare it as
sometype& function name (arguments);
If we wish our function to return an object of type sometype, but it is ok for it to return a copy of the object our function was working with then we can say
sometype function name (arguments);
Do I have this correct? And if so then what meaning would specifying an argument in a function as sometype* X have as in