c++arrayspointersconstantsreturn-by-reference

error: const method that returns an array of pointers by reference


class Board{
private:
    Shape shapes[100];
    Tile* tiles[16];
public:
    const Shape (&getShapes() const)[100]{return shapes;}; // (1) 
    const Tile* (&getTiles() const)[16]{return tiles;}; // (2)
};

I made this class called Board that has two methods returning an array by reference.

Method (2) reports an error:

qualifiers dropped in binding reference of type "const Tile *(&)[16]" to initializer of type "Tile *const [16]"

I fixed this error by writing const to the return type in method (1), but it doesn't work for method (2).

Why is this error occurring?


Solution

  • The element type of this array

     Tile* tiles[16]
    

    is Tile *. As the member function is a constant member function then the function should return the array by reference with constant elements. That is it should be declared like

    Tile* const (&getTiles() const)[16]{return tiles;}
    

    That is you may not assign new values to the pointers stored in the array.