0

I'm kind of confused about references in C++. Could anyone explain me this :

    class Dog
    {
        public:
            Dog( void ) {
                age = 3;
                name = "dummy";
            }

            void setAge( const int & a ) {
                age = a;
            }

         string & getName( void ) {
                return name;
            }

            void print( void ) {
                cout << name << endl;
            }

        private:
            int age;
            string name;

    };

int main( void ) {
    Dog d;
    string & name = d.getName(); // this works and I return reference, so the address of name will be the same as address of name in Dog class.

  int a = 5;
  int & b = a; // why this works? by the logic from before this should not work but the code below should.
  int & c = &a // why this does not work but the code above works?
}

Also when i remove & and make the function like this string getName the code won't work.

  • *this works and I return reference, so the address of name will be the same as address of name in Dog class.* Nope. Don't think of references as pointers. They can act like them and be implemented with them but they are not pointer. They are references. – NathanOliver Jul 06 '17 at 11:39
  • Some good reading: https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in – NathanOliver Jul 06 '17 at 11:41
  • I did not say they are pointers but the addresses of both variables are the same it's not like variable name from main functon has value which is address of variable name from Dog class. – stilltryingbutstillsofar Jul 06 '17 at 11:41
  • 1
    Consider references as alias.That's it.Don't think about addresses. – Gaurav Sehgal Jul 06 '17 at 11:41
  • @stilltryingbutstillsofar When you take the address of the reference you get the address of the thing the reference refers to, not the reference itself. Basically the reference just lets you call a variable a different name, but it is the same variable. – NathanOliver Jul 06 '17 at 11:43

1 Answers1

2

In case

 int & b = a;

b is reference to a and memory allocated for data of type int is available by both names a and b.

In case

 int & c = &a;

you are trying to save address of memory allocated for a - result of unary & - to int & c ... this lead to error.

In case of method

 string & getName( void )

reference to string is returned, so string & name (variable in main) will provide access to memory of private class member string name;

VolAnd
  • 6,367
  • 3
  • 25
  • 43