Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

4.5 Reference

1 min read
Image result for References are another variable type of C+

References are another variable type of C++ that act as an alias or short name to another variable. A reference variable acts just like the original variable it is referencing. References are declared by using an ampersand (&) between the reference type and the variable name.

Declaration
int distance = 5;
// normal integer
int &ref = distance;
// reference to distance
The ampersand in this context does not mean “address of”, it means “reference to”.

Use of reference
distance = 6;
// distance is now 6
ref = 7;
// distance is now 7

cout << distance; // prints 7
distance++;
cout << ref; // prints 8

Using the address-of operator on a reference returns the address of the value being referenced:
cout << &distance; // prints 0012FF7C
cout << &ref; // prints 0012FF7C

Const references
It is possible to declare a const reference. A const reference will not let you change the value it references: int distance = 5;
const int &ref = distance;

ref = 6; // illegal -- ref is const

                      4.6 Enumration and typedef          NEXT >>

You may like these posts

  •   Constructor A constructor is a special kind of class member function that is executed when an object of that class is instantiated. Constructors are typically used to init…
  • Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class). The…
  •   Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C++, this takes the form of a function that calls its…
  • Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. An object is an instanti…
  • You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of argu…
  • A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for f…

Post a Comment