Search code examples
c++visual-c++return-typequalifiers

C++ return type qualifiers heaven


It's hell actually. Can someone please explain in plain English why the below segments work or not?

class Hey;

class Bitmap {

public:
    const Hey* const& getHey() { return hey; }; // works
    const Hey* & getHey2() { return hey; }; // error C2440: 'return' : cannot convert from 'Hey *' to 'const Hey *&'

private:
    Hey* hey;
};

Solution

  • You can't add const to a pointer more than one type deep which is not itself const, because then you could stuff the address of a const variable into a non-const pointer. Consider:

    char c;
    char* p = &c;
    const char* cp = p; // ok, only one type deep
    const char x;
    cp = &x; // ok
    const char*& r = p; // fail, because...
    r = cp; // ok
    *p = 5; // ok, would overwrite a const variable if binding r to p were allowed
    

    Making the pointer const prevents this disaster a different way. Continuing the example:

    const char* const& cr = p; // ok
    cr = cp; // fail, cr is const, saving us from...
    *p = 5; // would overwrite a const variable if cr = cp were allowed