CPP Methods using References

Methods or functions using reference as arguments

  • Passing a reference to an object as an argument to a method or function involves only the reference of the object in the copy (you can nearly interpret reference as a const pointer).
  • When you pass a pointer reference to a function or method the object the pointer points to can be changed or accessed from inside the function if no restrictions are involved.
  • You are not able to change the reference itself from inside the function .
    Example of using reference to an object as argument to a method:
    #include <iostream>
    
    class Person
    {
    public:
    // This Constructor take two arguments of 
    // reference to integer
      Person (int & rAge, int & rWeight){
    // Set the age and weight before 
    // incrementing the references value
        this->age = rAge++;
        this->weight = rWeight++;
      }
      ~Person() {}
      int getAge() { return age; }
      int getWeight() { return weight; }
    
    private:
      int age;
      int weight;
    };
    
    int main() {
      int age=40;
      int weight=70;
    // Using Constructor that take arguments of 
    // reference to integer for age and weight as argument
      Person * pRicard = new Person(age, weight);
      std::cout << "Ricard is: ";
      std::cout << pRicard->getAge() << " years old.\n";
      std::cout << "And Ricard weighs: ";
      std::cout << pRicard->getWeight() << " kilo.\n\n" ;
    // Using Constructor that take arguments of 
    // reference to integer for age and weight as argument
    // but now age and weight are both incremented though Ricard object.
      Person * pObama = new Person(age, weight);
      std::cout << "Obama is: ";
      std::cout << pObama->getAge() << " years old.\n" ;
      std::cout << "And Obama weighs: ";
      std::cout << pObama->getWeight() << " kilo.\n\n" ;
      return 0;
    }
    When we run this application, the result will be:
    Ricard is: 40 years old.
    And Ricard weighs: 70 kilo.
    
    Obama is: 41 years old.
    And Obama weighs: 71 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.