views:

77

answers:

2

How do I return an array reference from a const member function?

class State{
    Chips (&arr() const)[6][7] { return arr_; }
    Chips val() const { return val_; }
}

Invalid initialization of reference of type 'Chips (&)[6][7]' from expression of type 'const Chips [6][7]'

Thank you.

+7  A: 

You got the syntax right, but if arr_ is an immediate member of the class (and it probably is), then you simply can't return a non-cost reference to this member. Inside the above arr method, member arr_ is seen as having const Chips[6][7] type. You can't use this type to initialize a reference of Chops (&)[6][7] type since it would break const-correctness. In order for the above to compile you'd need a const on the returned reference as well

...
const Chips (&arr() const)[6][7] { return arr_; }
...

But in any case, you'll be much better off with a typedef

...
typedef Chips Chips67[6][7];
const Chips67 &arr() const { return arr_; }
...
AndreyT
expected ';' before 'Chips'expected ';' before 'const'I tried that at first, but I got the above errors
david
@david : Edited. See again.
AndreyT
Thank you that worked perfectly
david
`const Chips ( }` works perfectly with g++-4.2, and I cannot see anything wrong with that syntax (besides the complexity to read it). What compiler are you using? (Anyway the typedef is almost a requirement for readability)
David Rodríguez - dribeas
A: 

You need to specify the function as returning a Chips pointer. So,

Chips* arr() const;

Is what you are looking for.

Alexander Rafferty
...I give up. .
Alexander Rafferty
I did not downvote, but the downvote may be because this answer does not solve the problem, nor would it compile. Returning a *decayed* pointer would be `const Chips (*arr() const )[7]` (and I am not even sure there). Note that only the outer array can/will decay automatically to a pointer, so if the type is `int array[3][4][5]`, it is an *array of 3 arrays of 4 arrays of 5 ints* when it decays it will be a *pointer to an array of 4 arrays of 5 ints*. Also, note that the problem is that with the member method being const, the returned element must also be const --or the compiler will complain.
David Rodríguez - dribeas
(1) The OP doesn't "need" to make the function return a pointer (2) Your "solution" doesn't work (3) This is not what the OP was looking for. So, basically, everything in this answer is wrong.
sellibitze