CPP References and const Modifier

Using const specifier with the Method's arguments.

  • If we in the Constructor do not want to give any possibility to change the integers original values then the Constructor must be as:
    // This Constructor take two arguments of 
    // reference to const integer
      Person (const int & rAge, const int & rWeight){
    // Set the age and weight 
    // We cannot changed the original integers now, only get them;
        this->age = rAge;       
        this->weight = rWeight; 
      }
  • If the argument to a method is of const object reference and you want to access any method in that object, these methods must be const specified :
    Example of a const object reference using methods of the object:
    #include <iostream>
    
    class Person {
    public:
    // This Constructor take two arguments of 
    //  reference to integer
      Person (int & age, int & weight){
    // Set the age and weight 
        this->age = age;
        this->weight = weight;
      }
    // This Constructor take arguments of 
    // reference to const object of Person
      Person (const Person & pPerson){
        this->age = pPerson.getAge()+1;
        this->weight = pPerson.getWeight()+10;
      }
       ~Person() {}
    // As we are using these methods in the last 
    // Constructor they must be supplied with the const specifier
      int getAge() const { return age; }
      int getWeight() const { return weight; }
    
    private:
      int age;
      int weight;
    };
    
    int main() {
      int age = 40;
      int weight = 60;
    // Using Constructor that take two arguments of 
    // reference to integer
      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 const object of Person
      Person * pObama = new Person(*pRicard);
      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: 60 kilo.
    
    Obama is: 41 years old.
    And Obama weighs: 70 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.