Difference between const ref and non-const ref: is my understanding comprehensive?

Discussion in 'C++' started by hbchen, Oct 26, 2007.

  1. hbchen

    hbchen New Member

    Joined:
    Oct 15, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    My Note about the difference between const ref and non-const ref
    (1)A non-const reference may be attached only to an object of the same type as the reference itself.
    (2)A const reference may be bound to an object of a different type but the change of that object will not change the reference.
    (3)A const reference can be bound to a variable of the same type, but you can not directly change the value of the const reference. However, any change of the variable will be reflected in the const reference.
    Below is my test code and results:
    Code:
    
    #include <stdio.h> 
    #include <conio.h>
    #include <iostream>
    
    void main() 
    {     
    
          double dval = 3.14;
          const int &ri = dval;
          const double &rd = dval;
          dval = 4;
        std::cout<< "dval= " << dval <<std::endl;//= 4
        std::cout<< "ri= " << ri <<std::endl; // =3
        std::cout<< "rd= " << rd <<std::endl; // =4
        _getch();
    }
    
    
    

    Please give your comments. Thanks!
     
  2. dharmaraj.guru

    dharmaraj.guru New Member

    Joined:
    Oct 23, 2007
    Messages:
    16
    Likes Received:
    0
    Trophy Points:
    0
    Explanation for the behaviour

    Hi,
    Here is the explanation for the behaviour.

    Reference is nothing but exactly const pointer, ie, address of the variable cannot be changed, but the value can be. When a variable is declared as const reference, its value also becomes unchangable. Hence, ultimately const reference is nothing but const pointer to const.

    By applying these rules, your observations can be easily understood.
    This is because, change in original must be reflected in the alias. This is not possible at run-time if alias and original are different types.
    Since, const reference cannot be changed in future, initialized value is type casted and assigned. In this case, compliler is not creating alias. Instead, it is creating a new const variable. You can confirm this by printing the address of both.
    For any reference variable, its value can be changed by accessing that memory through some other pointer. Here is the test code.
    Code:
    int main()
    {
    	const int &a = 2;
    	int *pa;
    
    	pa = (int *)&a;
    	*pa = 4;
    
    	cout << “a = ” << a << “ *pa = ” << *pa;
    	cout << “&a = ” << &a << “ pa = ” << pa;	
    }
    
    ||| Dharma |||
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice