3

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.

2 Answers 2

8

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_; }
...
Sign up to request clarification or add additional context in comments.

2 Comments

expected ';' before 'Chips' expected ';' before 'const' I tried that at first, but I got the above errors
const Chips (&arr() const)[6][7] { return err_; } 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)
-2

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

Chips* arr() const;

Is what you are looking for.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.