Thread: reference a const reference

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    40

    reference a const reference

    Hey all, I was just wondering why this won't compile.

    Code:
    int a=5;
    const int &b=a;
    int &c=b;                 //uh oh! why can't you reference a const ref?
    i mean, why not? what would be the problem if c changed? it only compiles if its constant.

    thanks for the help

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Well, consider this:
    Code:
    const int b = 5;
    int &c = b;
    If that compiled, then you could use c to change the (supposedly constant) value of b. Personally, I'm glad that the compiler won't let me do this. It keeps me from accidently changing a constant.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Code:
    int main() {
      int a;
    
      return f(a); // f accepts a const reference
                        // thus you can be sure a wont change with this function call
    }
    
    
    int f(const int &r_a) // const reference
    {
      // fortunately this is not possible:
      int &b = r_a; // !!! if that was possible a could change - even you said in the function head that a wont change... thats a contradiction...
    }

    if you could override "const" in such an easy way there would be no point in using const anyway...
    signature under construction

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    40
    of course. i forgot that references are implicit pointers. that was a pretty bad question. just goes to show what happens when you come back to c++ after a break

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. Replies: 4
    Last Post: 01-23-2008, 06:21 AM
  3. Need help implementing a class
    By jk1998 in forum C++ Programming
    Replies: 8
    Last Post: 04-05-2007, 03:13 PM
  4. const reference formal arguments
    By Chaplin27 in forum C++ Programming
    Replies: 8
    Last Post: 10-12-2004, 10:12 PM
  5. Problem with OpenGL tutorial
    By 2Biaz in forum Windows Programming
    Replies: 18
    Last Post: 09-16-2004, 11:02 AM