1

I have found a code construct, I have never seen before and I don't know how it is called. Can someone explain it to me? I was not able to find it via google nor in this forum.

module.cpp

namespace NSModule
{
    CModule CModule::Instance;    //Global in this namespace
}

module.hpp

namespace NSModule
{
   class CModule
   {
       public:
           /* Some methods and such stuff */

       private:
           static CModule Instance;
   }
}

Why is there the class before the variable together with :: ?

CModule CModule::Instance;

I will change the title and specify my question, when I know how this is called.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
CodingCat
  • 181
  • 1
  • 1
  • 9

2 Answers2

0

What you are looking at is known as a static class member:

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program. The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member:

class X { static int n; }; // declaration (uses 'static')
int X::n = 1;              // definition (does not use 'static')

As you can see in their example, when the variable is marked static, it is defined outside the class (unless for integral types such as int). Thus, in your code, the static CModule Instance; is being defined outside the class, where the definition calls the default constructor of the class CModule as follows:

  CModule  CModule::  Instance;
//type     class name variable name 
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

What you have discovered is the instantiation of a static class variable.

Until now a static variable from inside a class had to be instantiated OUTSIDE the class in which it was declared. The instantiation is done in the same way as declaring a normal variable.

So first there is the type of the variableCModule, then the variable nameCModule::Instance;.

Because this variable is from inside a class, to identify it correctly it has to be prefixed by the class name. The origin class name and variable name are separated by ::.

Since C++17:

A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify a default member initializer. It does not need an out-of-class definition...

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31