• 1

We recently found issue with our project caused by this error:

namespace sim

   class ClassA
      static std::list m_variable;

   std::list ClassA::m_variable;

So what happened is that m_variable became static for all instances of ClassA, not just for the particular instance of it. I'm not an expert with C++ so please bear with me if the problem is staring directly at my face, I'm still on the learning phase.

Can someone explain why this happened?

After your comment, you want to understand how to use static members of class.

For normal data members, one instance of the member exists in each and every instance of the class. OTOH a static data member exists only once and is shared among all object instances of the class.

Simply the simple declaration of a static member inside a class definition is only a declaration. Because of the One Definition Rule, that object also needs a definition.

In C++ language, that definition normally occurs outside of the class definition, so the line std::list<uint16_t> ClassA::m_variable; is required.

There are exception to that rule, mainly for static const integral members that can be defined inside the class definition provided you only use their value and not their address (search for One Definition Rule if you want to go further that way). But this is a rather advanced corner case, so if you are a beginner just remember that a static member of a class need a definition outside the class definition.

  • 1
Reply Report

Related Questions

Trending Tags