1

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

2
  • What's the int doing in your IDGenerator.cpp? Commented Mar 14, 2015 at 16:54
  • @user3528438 It's being defined and initialised there, absolutely correctly. It's a static member. Commented Mar 14, 2015 at 17:09

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

s_nNextID is private so you can't just access it like this. You need to make GetNextID a member of the class IDGenerator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.