Home > Net >  c 11: Why a in-class initialization of a static constexpr not a definition?
c 11: Why a in-class initialization of a static constexpr not a definition?

Time:09-17

Consider the simple following:

#ifndef TEST_H
#define TEST_H

class Test {
public:
    static constexpr int a = 1;
}

#endif

Note:

  1. There's no ODR violation due to the macro.
  2. Why the constexpr static int a not considered a definition since it's defined in the class Test? Because it's not a definition, hence it needs the below outside of the class. Why?

constexpr int Test::a;

CodePudding user response:

Why a in-class initialization of a static constexpr not a definition?

Because of One Definition Rule (ODR). The rule says that there must be exactly one definition of each non-inline non-member and static member variable. Class definitions, due to their nature, are typically included into multiple translation units. If class definition contained a variable definition, then inclusion into multiple translation units would violate the ODR.

Since C 17, the language has inline variables, so you can define such inline variables within class definitions.

  • Related