Home > Blockchain >  Why can't I define a static class member field in .hpp?
Why can't I define a static class member field in .hpp?

Time:12-06

class TestClass
{
public:
    static int testMember;

    template<class T> static  T* Foo()
    {
        //Defination....
    }
}
//int TestClass::testMember;  //Duplicate definition

Why can't I define a member field in .hpp while I can define member functions in .hpp?

Does it must be defined in a .cpp file?

CodePudding user response:

Why can't I define a member field in .hpp

You can.

C doesn't care what you name your files, and doesn't care what extension the files have.

What you can't do is define the variable more than once. That would obviously violate the one definition rule.

In order to satisfy the one definition rule, you have two options:

  • In C 17 or later, make the variable inline.

    class TestClass
    {
    public:
      static inline int testMember;
    
      template<class T> static  T* Foo()
      {
          //Defination....
      }
    }
    
  • In any version of C , place the definition in your code where it will be compiled exactly once.

Why ... [can I] define member functions in .hpp?

Because member functions, defined in the class, are implicitly inline. Just like your variable could be.

CodePudding user response:

As Drew Dormann has mentioned, template member functions (static or not) are implicitly inline.
The same goes for class templates:

template <typename>
class TestClass
{
public:
    static int testMember;

    template<class T> static  T* Foo()
    {
        //Definition....
    }
};

// prior to C  17 you definition MUST be outside the class in the header
template <typename T>
int TestClass<T>::testMember{};
  •  Tags:  
  • c
  • Related