C++ return type qualifiers heaven

284 Views Asked by At

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;
};
3

There are 3 best solutions below

0
On BEST ANSWER

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
0
On

The compiler doesn't see "Hey*" and "const Hey*" as the same so it doesn't want to convert the reference whereas he convert the const reference (similar to parameter conversion)

0
On

A const reference can be initialized to an object of a different type or to an rvalue , such as a constant expression:

  const int i = 42;
  //  legal for const references only
  const int &r = i;

The same initializations are not legal for nonconst references.

You are trying to initialize reference with const expression. Const expression is rvalue. The const reference can be initialize with rvalue, while non const can't.

Edit: About rvalues and lvalues you can read in weakipedia .