Search code examples
c++pointersreferenceconstantslvalue

"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


Solution

  • 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.