CPP Create and Use References

What is a C++ Reference?

  • A reference is an alias; when you create a reference, you initialize it with the name of another object, the target.
  • So you can create a reference by:
    1. Writing the type of the target object
    2. followed by the reference operator (&),
    3. followed by the name of the reference,
    4. followed by an equal sign,
    5. followed by the name of the target object.

    int & rNumber = Number;
  • DON'T try to reassign a reference or set it to null - it is not permitted in C++.
  • DON'T confuse the address-of operator with the reference operator.
      int Number =5;
      int & rNumber = Number; // rNumber is a reference to rNumber 
                              // so to print rNumber or Number result in the same (5)
      //  Using the address-of (&) operator 
      int * pNumber = &Number;    // As rNumber is a reference to 
      int * prNumber = &rNumber;  // Number the addresses have to be equal
      std::cout << "Address:" << pNumber << " = " << prNumber  << "\n";
    

Referencing Objects

  • You can make a reference to any created object of any class, but not the class.
  • Any public member of a referenced object can be accesses using the dot (.) operator.
    Example using object reference:
    #include <iostream>
    
    class Person
    {
    public:
      Person (int age, int weight){
        this->age = age;
        this->weight = weight;
      }
      ~Person() {}
      int getAge() { return age; }
      int getWeight() { return weight; }
    private:
      int age;
      int weight;
    };
    
    int main()
    {
      Person Ricard(50,80);
      // referencing Ricard
      Person & rRicard = Ricard;
    
      std::cout << "Ricard is: ";
      std::cout << Ricard.getAge() << " years old." << std::endl;
      std::cout << "And Ricard weighs: ";
      // using the reference
      std::cout << rRicard.getWeight() << " kilo." << std::endl;
      return 0;
    }
    When we run this application, the result will be:
    Ricard is: 50 years old.
    And Ricard weighs: 80 kilo.

    You can download this example here (needed tools can be found in the right menu on this page).


© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.