Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static constant array initialization inside class

Tags:

c++

c++11

I want to create a constant and static integer array as a public class variable. It is neat to define it and initialize it right away. See code below for complete example.

#include <iostream>

class Foo {
public:
    constexpr static int arr[3][2] = {
            {1, 2},
            {3, 4},
            {5, 6}
    };
};

int main() {
    for (int i = 0; i < 3; i++) {
        std::cout << "Pair " << Foo::arr[i][0] << ", " << Foo::arr[i][1] << std::endl;
    }
    return 0;
}

However, compiling code above using g++ --std=c++11 test.cpp produces

/usr/bin/ld: /tmp/ccc7DFI5.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Foo::arr'
/usr/bin/ld: test.cpp:(.text+0x55): undefined reference to `Foo::arr'
collect2: error: ld returned 1 exit status

Is this not possible in C++ ? More likely I am missing some part about C++ and its static variable initialization policy.

like image 270
Talos Avatar asked Mar 01 '23 17:03

Talos


1 Answers

Before C++17 (so C++11 and C++14) you have to add

constexpr int Foo::arr[3][2];

outside the body of class.

like image 179
max66 Avatar answered Mar 16 '23 23:03

max66