Search code examples
c++pointersreferencecoding-styleaddress-operator

Whats the difference between Reference and Pointer return types in C++


If I were to create a simple object in C++, what is the difference between returning an address of the member vs. returning a pointer. As far as I'm aware, C++ doesn't have automatic garbage collection so it wouldn't be keeping a reference count. So why would someone do it this way:

class CRectangle {
public:
    string& getName( );
    int&    getWidth( );
    int&    getHeight( );
private:
    string  name;
    int     height;
    int     width;
};

rather than this way:

class CRectangle {
public:
    string* getName( );
    int*    getWidth( );
    int*    getHeight( );
private:
    string  name;
    int     height;
    int     width;
};

I realize these would allow you to access member data, but I'm not concerned about proper encapsulation in this simple example. So whats the difference? Speedup? Readability? Style?


Solution

  • The & (in this context) doesn't mean "address of".

    A function declared as string& getName( ); returns a reference, not a pointer. A reference is essentially an alias for another object. So in this case, it doesn't return a copy of the object's name, or a pointer to the name, but a reference to the name itself. So any changes to the returned object are directly applied to the object's name.

    You could achieve the same by returning a pointer, but there'd be two significant differences:

    • a pointer requires special syntax to access (the * and -> operators), whereas a reference is used the exact same way you'd use the object itself.
    • a pointer can be null, a reference cannot. So any time a pointer is used, you are signalling to the reader of the code that "this value may be null"