Overriding a method returning a reference to an array does not work in gcc, but works in clang/icx

I want to return a reference to an array in C++. I am referring to the getColor2 member function and its overrides in the example below.

I have a pure virtual member function in my base class ILed:

[[nodiscard]] virtual const uint8_t (&getColor2() const)[4] = 0

I have this method in a sub class HardwareLed:

[[nodiscard]] const uint8_t (&getColor2() const)[4] override;

I'd expect the latter function to override the former, but when using gcc (e.g. 13.2), I get these error message:

<source>:62:53: error: expected ';' at end of member declaration
   62 |   [[nodiscard]] const uint8_t (&getColor2() const)[4] override;
      |                                                     ^
      |                                                      ;
<source>:62:55: error: 'override' does not name a type
   62 |   [[nodiscard]] const uint8_t (&getColor2() const)[4] override;

Using the same source code, but with clang 17.0.1 or icx 2023.2.1 does not yield these errors and the application compiles successfully.

Here's the complete example: https://godbolt.org/z/d7j7ozKbM

I could just resort to using the raw pointer to the array (perhaps with a struct and a reinterpret_cast instruction), but it seems not as good of a solution to me. getColor (without the 2) is implemented that way.

Also I'd file a bug in GCC, but I am not sure if they will let me (GCC bugzilla states, that I'll get an invitation soon?) and they have a lot of known issues and I cannot exactly determine if this is one of them (e.g. incomplete types) as I am a bit of a C++ newbie.

Any help is greatly appreciated!


  • First of all, it is not intrinsically wrong to return a reference to an array member. It is quite different from attempting to return an array from a free function. Additionally, GCC just uses a different syntax, and it looks like a bug to me but I need some language lawyer to confirm this. To make your code compile on gcc, use the following instead.

    [[nodiscard]] const uint8_t (&getColor2() const override)[4];

    Demo: https://godbolt.org/z/xMqPzT1vc