Need help c++ reference.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • carbon
    New Member
    • Mar 2014
    • 9

    #1

    Need help c++ reference.

    Code:
    int main(){
    	char const &rr = 'x';	 //works
    	//const char &rr = 'x';	   works
    
    	char a[5] = "Hi!";
    	char* const &r = a; 	//works
    	//const char*  &r = a;	  doesn't works
    
    	std::cout << rr << std::endl;
    	std::cout << r[2] << std::endl;
    	system("pause");
    	return 0;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This code:

    Code:
    char a[5] = "Hi!";
    defines a as the address of a[0]. Therefore, a is a char*.

    This code:
    Code:
    //const char*  &r = a;      doesn't works
    attempts to define r as a reference to a variable that is a const char* The variable a is not const and so you can't use it to create a reference that is const.

    Remember, in C++, that a reference is just another name for an already existing variable. Because of this, you can't have the reference const and the variable not const. The reference and the variable are the same variable.

    Comment

    • carbon
      New Member
      • Mar 2014
      • 9

      #3
      I have cleared my doubts.

      Cv-qualifiers like const apply to whatever is to the left of them, unless there is nothing, in which case they apply to the right.

      Code:
      char* const &r = a;
      The above code works because here, r has been declared a reference to a constant pointer that is pointing to a character type.


      Code:
      const char*  &r = a;
      The above code doesn't work as here, r has been declared as a reference to a pointer that is pointing to a constant character.

      Thanks Anyways ;)

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        So you see now that problem was not with references but with what was const.

        It's OK to have a const reference to something not const because if the something changes the const-ness of the reference does not.

        But you may not define a reference to a const something if the something is not const. If the something changes, the reference to const is violated.

        Comment

        Working...