Milad Sobhkhiz
Milad Sobhkhiz

Reputation: 1159

What is the meaning of & in c++?

I want to know the meaning of & in the example below:

class1 &class1::instance(){

///something to do

}

Upvotes: 3

Views: 20550

Answers (6)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

The & operator has three meanings in C++.

  • "Bitwise AND", e.g. 2 & 1 == 3
  • "Address-of", e.g.: int x = 3; int* ptr = &x;
  • Reference type modifier, e.g. 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).

Upvotes: 8

learnerNo1
learnerNo1

Reputation: 147

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...

Upvotes: 0

Thomas Jones-Low
Thomas Jones-Low

Reputation: 7161

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;

Upvotes: 0

Wim
Wim

Reputation: 11242

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:

  • can never be undefined / NULL
  • you can't do pointer arithmetic with them

So they are a sort of light, safer version of pointers.

Upvotes: 7

Puppy
Puppy

Reputation: 146910

It returns a reference to an object of the type on which it was defined.

Upvotes: 1

stefan
stefan

Reputation: 2886

Its a reference (not using pointer arithmetic to achieve it) to an object.

Upvotes: 1

Related Questions