Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"non-const lvalue reference to type cannot bind" error with reference (Type &) but not with pointer (Type *)

I am getting this error "Non-const lvalue to type 'Cell' cannot bind to a temporary of type 'Cell *' with this code :

class RegionHolder
{    
public:
    RegionHolder(Region& Region1):m_RegionCellNOO(&(Region1.m_NOO))
    ~RegionHolder();

protected:
    Cell & m_RegionCellNOO; // difference is here   
};

but not with this one :

class RegionHolder
{    
public:
    RegionHolder(Region& Region1):m_RegionCellNOO(&(Region1.m_NOO))
    ~RegionHolder();

protected:
    Cell * m_RegionCellNOO; // difference is here   
};

I don't understand the problem and would really like to use references and not pointers.

Thanks

like image 910
Alexis Cofion Avatar asked Dec 26 '22 09:12

Alexis Cofion


1 Answers

You forgot to show us the definition, but presumably Region1.m_NOO is an object of type Cell. Your first example is taking the address of it, and trying to use the resulting pointer to initialise a reference. References aren't initialised from pointers, but from the object itself:

RegionHolder(Region& Region1):m_RegionCellNOO(Region1.m_NOO) {}
//                                            ^ no &         ^^ don't forget that

There is one caveat with using references rather than pointers: they are not assignable, and so neither is your class. Often that's not a problem; but if you do need your class to be assignable, then you'll need to use a pointer instead.

like image 93
Mike Seymour Avatar answered Feb 02 '23 00:02

Mike Seymour