What is the meaning of & in c++?

20,492

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

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

Share:
20,492
Milad Sobhkhiz
Author by

Milad Sobhkhiz

Updated on March 14, 2020

Comments

  • Milad Sobhkhiz
    Milad Sobhkhiz over 4 years

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

    class1 &class1::instance(){
    
    ///something to do
    
    }