Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 331
Bill Kotsias Avatar asked Jan 20 '23 13:01

Bill Kotsias


2 Answers

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
like image 148
Ben Voigt Avatar answered Jan 30 '23 08:01

Ben Voigt


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 .

like image 42
UmmaGumma Avatar answered Jan 30 '23 06:01

UmmaGumma