Search code examples
c++staticinitializationprivate

Initializing a private static member variable in the cpp file. error: member is private


Here is a simple example illustrating my problem.

IDGenerator.hpp

#ifndef IDGENERATOR_HPP_
#define IDGENERATOR_HPP_

class IDGenerator {

   private:
      static int s_nNextID;

      // make the IDGenerator class a static class with a private default constructor
      IDGenerator();

   public:
      static int GetNextID();

};

#endif

IDGenerator.cpp

#include "IDGenerator.hpp"

// initialize the static id
int IDGenerator::s_nNextID(1);

int GetNextID()
{
   return IDGenerator::s_nNextID++;
}

I have tried initializing both explicitly (int IDGenerator::s_nNextID = 1;) and implicitly as shown. Here is the compile command and the error

g++ -c IDGenerator.cpp
IDGenerator.cpp: In function ‘int GetNextID()’:
IDGenerator.cpp:11:5: error: ‘int IDGenerator::s_nNextID’ is private
 int IDGenerator::s_nNextID(1);
     ^
IDGenerator.cpp:15:22: error: within this context
  return IDGenerator::s_nNextID++;

I have also tried to compile with -Wall and std=gnu++11. Same error


Solution

  • The error isn't about the initialization. It just points to the initialization as the point where s_nNextID comes from.

    The real error is on line 15, where you access s_nNextID from a normal global function, because you forgot the IDGenerator:: in the definition head of GetNextID.