C++

C++ TutorialBasic input/output in c++C++ AlignmentC++ Argument Dependent Name LookupC++ Arithmitic MetaprogrammingC++ ArraysC++ Atomic TypesC++ AttributesC++ autoC++ Basic Type KeywordsC++ Bit fieldsC++ Bit ManipulationC++ Bit OperatorsC++ Build SystemsC++ C incompatibilitiesC++ C++11 Memory ModelC++ Callable ObjectsC++ Classes/StructuresC++ Client server examplesC++ Common compile/linker errors (GCC)C++ Compiling and BuildingC++ Concurrency with OpenMPC++ Const CorrectnessC++ const keywordC++ Constant class member functionsC++ constexprC++ ContainersC++ Copy ElisionC++ Copying vs AssignmentC++ Curiously Recurring Template Pattern (CRTP)C++ Date and time using chrono headerC++ Debugging and Debug-prevention Tools & TechniquesC++ decltypeC++ Digit separatorsC++ EnumerationC++ ExceptionsC++ Explicit type conversionsC++ Expression templatesC++ File I/OC++ Floating Point ArithmeticC++ Flow ControlC++ Fold ExpressionsC++ Friend keywordC++ function call by value vs. call by referenceC++ Function OverloadingC++ Function Template OverloadingC++ Futures and PromisesC++ Header FilesC++ Implementation-defined behaviorC++ Inline functionsC++ Inline variablesC++ IterationC++ IteratorsC++ KeywordsC++ LambdasC++ Layout of object typesC++ Linkage specificationsC++ LiteralsC++ LoopsC++ Memory managementC++ MetaprogrammingC++ Move SemanticsC++ mutable keywordC++ MutexesC++ NamespacesC++ Non-Static Member FunctionsC++ One Definition Rule (ODR)C++ Operator OverloadingC++ operator precedenceC++ OptimizationC++ Overload resolutionC++ Parameter packsC++ Perfect ForwardingC++ Pimpl IdiomC++ PointersC++ Pointers to membersC++ PolymorphismC++ PreprocessorC++ ProfilingC++ RAII: Resource Acquisition Is InitializationC++ Random number generationC++ Recursive MutexC++ Refactoring TechniquesC++ ReferencesC++ Regular expressionsC++ Resource ManagementC++ Return Type CovarianceC++ Returning several values from a functionC++ RTTI: Run-Time Type InformationC++ Scopes



C++ References

From WikiOD

Defining a reference[edit | edit source]

References behaves similarly, but not entirely like const pointers. A reference is defined by suffixing an ampersand & to a type name.

int i = 10;
int &refi = i;

Here, refi is a reference bound to i.

References abstracts the semantics of pointers, acting like an alias to the underlying object:

refi = 20; // i = 20;

You can also define multiple references in a single definition:

int i = 10, j = 20;
int &refi = i, &refj = j;

// Common pitfall :
// int& refi = i, k = j;
// refi will be of type int&.
// though, k will be of type int, not int&!

References must be initialized correctly at the time of definition, and cannot be modified afterwards. The following piece of codes causes a compile error:

int &i; // error: declaration of reference variable 'i' requires an initializer

You also cannot bind directly a reference to nullptr, unlike pointers:

int *const ptri = nullptr;
int &refi = nullptr; // error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'nullptr_t'

C++ References are Alias of existing variables[edit | edit source]

A Reference in C++ is just an Alias or another name of a variable. Just like most of us can be referred using our passport name and nick name.

References doesn't exist literally and they don't occupy any memory. If we print the address of reference variable it will print the same address as that of the variable its referring to.

int main() {
    int i = 10;
    int &j = i;

    cout<<&i<<endl;
    cout<<&b<<endl;
    return 0;
}

In the above example, both cout will print the same address. The situation will be same if we take a variable as a reference in a function

void func (int &fParam ) {
   cout<<"Address inside function => "<<fParam<<endl;
}

int main() {
    int i = 10;
    cout<<"Address inside Main => "<<&i<<endl;    

    func(i);

    return 0;
}

In this example also, both cout will print the same address.

As we know by now that C++ References are just alias, and for an alias to be created, we need to have something which the Alias can refer to.

That's the precise reason why the statement like this will throw a compiler error

int &i;

Because, the alias is not referring to anything.

Credit:Stack_Overflow_Documentation