Hello if I have a static const
data member then I can provide an in-class initializer for it and I don't need to define it again outside of the class body.
But that is true only if that constant is used within the class scope and if used outside, a separate definition outside must be supplied otherwise any reference to it causes a link-time error: "undefined reference to static object: x".
struct Foo{ static int const sz_ = 100; std::array<int, sz_> ai_100{}; }; //int const Foo::sz_; int main(){ float pts[Foo::sz_]{}; // ok void bar(int const&); // defined later on bar(Foo::sz_); // undefined reference to Foo::sz_ } void bar(int const&){ //do_something }
Why when used the
static const
data membersz_
outside of the class scope as the array size is OK?Why when passing
sz
to functionbar
which takes an l-value reference toconst
the linker fails to link and complain about the definition ofFoo::sz_
?The function
bar
takes an l-value reference toconst int&
so it can be initialized from an r-value so why it matters about the definition of the initializerFoo::sz_
?