5

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

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Alexis Cofion
  • 83
  • 1
  • 2
  • 5
  • 4
    For one, you're trying to assign an address to a reference in the first block. – Dan F Feb 07 '13 at 15:10
  • 2
    `&(Region1.m_NOO)` is a pointer. Of course you can't bind an `int&` to an `int*`, so why should it be different for a `Cell&` and `Cell*`? – Daniel Fischer Feb 07 '13 at 15:13

2 Answers2

8

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

The unary & operator gets a pointer to a variable. So, in C++ (as in C) a = &b gets a pointer to b and stores this value in a, so if b is of type int, a needs to be of type int*. Assignment to references, on the other hand, is implicit, so if a is of type int& you simply need to write a=b to make a a reference to b. So in your case, you need to rewrite your constructor as

RegionHolder(Region& Region1):m_RegionCellNOO(Region1.m_NOO) {}

However, I think you're better off using pointers than references here anyway and trying to use C++ without getting comfortable with pointers is a very bad idea. So I suggest you take the time to make yourself comfortable with using pointers instead of trying to avoid them.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
  • Great, I'll try to stick with pointers then. Is there any way I can access Region1.m_NOO if this variable is private within Region class? – Alexis Cofion Feb 07 '13 at 16:04
  • No, that's the point of `private`. If you want to access it you need to either (1) make `RegionHolder::RegionHolder` a friend of `Region` or (2) add an accessor function to `Region`, e.g. `Region* GetNOO() { return &m_Noo; }` – Jack Aidley Feb 07 '13 at 16:16