I want to know the meaning of & in the example below:
class1 &class1::instance(){
///something to do
}
This means your method returns a reference to a method1 object. A reference is just like a pointer in that it refers to the object rather than being a copy of it, but the difference with a pointer is that references:
So they are a sort of light, safer version of pointers.
Its a reference (not using pointer arithmetic to achieve it) to an object.
It means that the variable it is not the variable itself, but a reference to it. Therefore in case of its value change, you will see it straight away if you use a print statement to see it. Have a look on references and pointers to get a more detailed answer, but basecally it means a reference to the variable or object...
The &
operator has three meanings in C++.
2 & 1 == 3
int x = 3; int* ptr = &x;
int x = 3; int& ref = x;
Here you have a reference type modifier. Your function class1 &class1::instance()
is a member function of type class1
called instance
, that returns a reference-to-class1
. You can see this more clearly if you write class1& class1::instance()
(which is equivalent to your compiler).
It returns a reference to an object of the type on which it was defined.
In the context of the statement it looks like it would be returning a reference to the class in which is was defined. I suspect in the "Do Stuff" section is a
return *this;