Thread: help needed with References

  1. #1
    Unregistered
    Guest

    help needed with References

    hi,
    I have several questions......

    1) Please explain what are references and how it is different form pointers.
    2)Considerr the following code.(extraced form "C++ in 21 days")

    class Cat {
    public :
    /* code appears here */
    ...........
    ..........
    const Cat & operator++();
    private :
    int itsValue;
    }

    const Cat& Cat:perator++(){
    ++itsValue;
    return *this;
    }

    void main(){
    Cat a;
    Cat b=a++;
    }

    (i) In this code, the overloaded "++" operator returns the object itself. But the prototype of the function says it returns a reference to a Cat object.

    (ii)And this return value (the reference to Cat object) is assigned to a Cat type variable. How is this possible ?
    Please Explain.

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    >1) Please explain what are references and how it is different form pointers.<

    They are like pointers, in that they can be used to refer to another variable rather than a value, but cannot be used to directly manipulate memory.

    >(i) In this code, the overloaded "++" operator returns the object itself. But the prototype of the function says it returns a reference to a Cat object.<

    Yes because you can assign a variable to a reference. *this is a Cat, you are returning a reference to *this, which is ok because it will exist after the function has returned.

    >(ii)And this return value (the reference to Cat object) is assigned to a Cat type variable. How is this possible ?<

    You can assign a reference to a variable. This will assign the value refered to by the reference (a copy of the original variable).

    int a = 10;
    //assign a variable to a reference
    int& ra = a;

    int b=0;
    //assign a reference to a variable
    b=ra;

    b is now an independent variable that contains the value that ra refered to.

    Arguably one of the disadvantages of references is that they're not as explicit as pointer notation so it's harder to see what's giong on, but if you understand how the above would be done with pointers, you shouldn't have too much trouble figuring out how it works.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiler settings, references etc...
    By ejohns85 in forum C++ Programming
    Replies: 0
    Last Post: 05-14-2009, 04:53 AM
  2. Pointers and references?!? Help!
    By alyeska in forum C++ Programming
    Replies: 3
    Last Post: 10-30-2008, 10:23 AM
  3. Replies: 2
    Last Post: 05-23-2008, 05:49 AM
  4. Arrays of references
    By Welshy in forum C++ Programming
    Replies: 16
    Last Post: 07-04-2005, 11:28 PM
  5. declare references to references works!
    By ManuelH in forum C++ Programming
    Replies: 4
    Last Post: 01-20-2003, 08:14 AM