0

I have TestMethods.h

#pragma once // strings and c-strings #include <iostream> #include <cstring> #include <string> class TestMethods { private: static int nextNodeID; // I tried the following line instead ...it says the in-class initializer must be constant ... but this is not a constant...it needs to increment. //static int nextNodeID = 0; int nodeID; std::string fnPFRfile; // Name of location data file for this node. public: TestMethods(); ~TestMethods(); int currentNodeID(); }; // Initialize the nextNodeID int TestMethods::nextNodeID = 0; // I tried this down here ... it says the variable is multiply defined. 

I have TestMethods.cpp

#include "stdafx.h" #include "TestMethods.h" TestMethods::TestMethods() { nodeID = nextNodeID; ++nextNodeID; } TestMethods::~TestMethods() { } int TestMethods::currentNodeID() { return nextNodeID; } 

I've looked at this example here: Unique id of class instance

It looks almost identical to mine. I tried both the top solutions. Neither works for me. Obviously I'm missing something. Can anyone point out what it is?

7
  • Whats the problem with using static int nextNodeID = 0; in the class? You can still increment it in your constructor. Commented Mar 14, 2018 at 14:58
  • 1) "I tried this down here ... it says the variable is multiply defined." Don't define the variable in the header - do it in the .cpp file, so it is defined only once. 2) "it says the in-class initializer must be constant" Are you compiling with C++-11 enabled? If I remember correctly, such syntax was invalid before C++-11. Commented Mar 14, 2018 at 14:58
  • Nathan, the problem is that it says "a member with an in-class initializer must be const" ... but this is not intended to be a constant. Commented Mar 14, 2018 at 15:03
  • Algirdas, If I put it outside the class definition, it's no longer a private variable. However, I tried that and it works. I don't know how to tell what version of C++ I'm compiling to. I just installed VS community 2017. There is nothing entered in the "C++ Language Standard" Commented Mar 14, 2018 at 15:09
  • Oh, oops. Forgot that in class initialization still doesn't apply for non-const static members Commented Mar 14, 2018 at 15:11

1 Answer 1

2

You need to move the definition of TestMethods::nextNodeID into the cpp file. If you have it in the header file then every file that includes the header will get it defined in them leading to multiple defenitions.

If you have C++17 support you can use the inline keyword to declare the static variable in the class like

class ExampleClass { private: inline static int counter = 0; public: ExampleClass() { ++counter; } }; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.