This question already has answers here:
How to initialize private static members in C++?
(18 answers)
Closed 8 years ago.
I have a class like this:
class example {
public:
static void setStaticVar() { example::var = 1; };
private:
static int var;
};
But it gives me linker errors and I have no idea why.
I want to store some data in the variable that is the same for every instance. That's why I want to use a static variable instead of an instance variable (with an instance variable I would store the same data in every single instance of the class which is a waste of memory).
How do I do this?
In the source file
int example::var = 0;
You need to initialize the variable once. In one .cpp, outside of any functions, you have to initialize the variable:
int example::var = 0;
You must initialize it out of the class definition.
Try this.
class example { ... };
// initialize it to avoid linker errors
int example::var = 1;
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a struct defined in a header file. Then I have a singleton class where I am trying to use the struct. When I call ResetVars() from another class I get an access violation when it hits the line that says test.numResponses = "TEST". I am assuming this has something to do with initialization but I haven't been able to solve it. I am new to c++ and I have no idea how to get around this. Thanks for any help.
struct.h
typedef struct POLL_DATA
{
std::string numResponses;
std::string type;
std::string question;
} POLL_DATA;
ControlPolls.h
class ControlPolls
{
private:
static bool instanceFlag;
static ControlExitPolls *controlSingle;
ControlExitPolls();
POLL_DATA test;
public:
static ControlExitPolls* getInstance();
void ResetVars();
};
ControlPolls.cpp
#include "ControlPolls.h"
bool ControlPolls::instanceFlag = false;
ControlPolls* ControlPolls::controlSingle = NULL;
//Private Constructor
ControlExitPolls::ControlExitPolls()
{
};
//Get instance
ControlPolls* ControlPolls::getInstance()
{
if(!instanceFlag)
{
controlSingle = &ControlPolls();
instanceFlag = true;
return controlSingle;
}
else
{
return controlSingle;
}
}
void ControlExitPolls::ResetVars()
{
test.numResponses = "TEST";
}
callingClass.cpp
ControlPolls *controlSingleton;
controlSingleton = ControlPolls::getInstance();
controlSingleton->getInstance()->ResetVars();
You've been struck by C++'s Most Vexing Parse, a compiler rule that says anything that could be a function declaration is a function declaration. The culprit is this line:
POLL_DATA testPoll();
testPoll is treated as the declaration of a function with return type POLL_DATA. Try removing the brackets, or writing simply POLL_DATA testPoll; which implicitly calls the compiler-generated default constructor.
Another larger problem is that testPoll is a member of A, but you've hidden it and declared a local variable in your constructor, A::A(). I suggest you remove the constructor altogether because the implicit constructor will suffice.
Some more notes on your code:
You've declared your class a but refer to it later as A.
You've written an implementation of a constructor for A without declaring it like a proper forward declaration.
Also, typedef struct is not needed in C++. It is sufficient and encouraged to write:
struct POLLDATA {
...
};
This question already has answers here:
What is the lifetime of a static variable in a C++ function?
(5 answers)
Closed 6 years ago.
recently I saw a piece of code as follows :
namespace {
mutex* get_server_factory_lock() {
static mutex server_factory_lock;
return &server_factory_lock;
}
typedef std::unordered_map<string, ServerFactory*> ServerFactories;
ServerFactories* server_factories() {
static ServerFactories* factories = new ServerFactories;
// is variable factories assigned every time this function called ?
return factories;
}
} // namespace
/* static */
void ServerFactory::Register(const string& server_type,
ServerFactory* factory) {
mutex_lock l(*get_server_factory_lock());
if (!server_factories()->insert({server_type, factory}).second) {
LOG(ERROR) << "Two server factories are being registered under "
<< server_type;
}
}
It seems that function server_factories() is similar to the singleton.
My question is : to the best of my knowledge, factories is a static variable, and every time function server_factories() called, this static variable will be assigned a new value. But the result is not, every time server_factories() is called, it returns the same pointer. Why?
PS : with c++11 enabled when compiling.
Duplicated with What is the lifetime of a static variable in a C++ function?
It's a static, so it only gets initialized once, when you first enter the function. Later calls to the same function use the previous variable. That said, I fail to see why it's a pointer and not a simple function static variable (with automatic storage duration) that we could take the address of...
This question already has answers here:
Unresolved external symbol on static class members
(6 answers)
Closed 7 years ago.
I'm currently designing some code on QT that is built across multiple source. I want to create an array in one source and be able to access it in another source.
Currently in my Header I have class
Array_Class : public QString
{
public:
static QString Data_Array [2];
};
I don't think I need a constructor as I'm going to "populate" the array before I read it.
currently in my source.cpp I have
Array_Class::Data_Array[0]= "foo";
Array_Class::Data_Array[1]= "bar";
however this gives me the error message undefined reference to "Array_Class::Data_Array". What am I missing? thanks
So far, you have only declared your array:
Array_Class : public QString
{
public:
static QString Data_Array [2]; // -> only a declaration!
};
In order to use it, you must now define it. To do this, you need to place somewhere in your .cpp:
QString Array_Class::Data_Array [2];
This question already has answers here:
Defining static members in C++
(6 answers)
Closed 7 years ago.
I need a class with static std::vector<int> simples (first N simple numbers). I created it in static method __init__, which is called before any instance of MyClass is created:
class MyClass
{
public:
MyClass()
{
/* I need to use MyClass::simples here */
printf("%d\n", (int)MyClass::simples.size());
/* But I get the error here :( */
}
static void __init__(int N)
{
simples.push_back(2);
/* ...
here I compute first N simple numbers and fill
MyClass::simples with them
*/
}
private:
static std::vector<int> simples;
};
int main()
{
MyClass::__init__(1000);
MyClass var;
return 0;
}
But when I tried to use this vector in construction, I get undefined reference to 'MyClass::simples' error. How to solve my problem?
When defining a static member in C++, you need to write it two times: first in class definition as you did:
static std::vector<int> simples;
And then outside (preferably in an external .cpp file):
std::vector<int> MyClass::simples;
If you know about C language, this can help you: static members in C++ are comparable from global variables in C: defined as a prototype in .h file included whenever you need it, and value initialized in one .c/.cpp file.
You have to define the static data member outside the class
std::vector<int> MyClass::simples;
Within the class definition it is only declared.
This question already has answers here:
Static variable for object count in c++ classes?
(3 answers)
Closed 3 months ago.
I would like to achieve a functionality where I can know how much object where created using a specific class.
I have tried the following:
myClass.h
class myClass {
private:
static int internalCounter;
int id;
public:
myClass(): id(internalCounter) {internalCounter++;}
}
The problem is that C++ doesn't allow this, and I'm not sure how to workaround this.
I have seen similar question in SA in which answer suggested something like:
myClass::internalCounter = 0;
But I don't think this right on the syntax level.
C++ does allow this. But the static variable needs a definition, and it sounds like that's missing. You'll need to put this in a source file (not the header)
int myClass::internalCounter = 0;
The = 0 is optional, since static variables are zero-initialised by default, but you might prefer to be explicit.
You need to define your static variable as
int myClass::internalCounter = 0;
in an implementation file.
The other suggestion you saw was almost right. You need something like this:
int myClass::internalCounter = 0;
But it needs to go in a source file (*.cpp) rather than a header. That line is necessary because the declaration on its own (in the header file) would never be instantiated otherwise. Resolving it in a source file means it will get picked up and instantiated within a specific translation unit.
You must define your static variable:
int myClass::internalCounter=0;
in your implementation file, its always best to read your compiler/linker output, in case of g++ it is:
main.cpp:(.text.startup+0x2): undefined reference to `myClass::internalCounter'
undefined reference means it was not defined, this is a hint on what you must fix in your code
I will suggest that, as you need to put your counter into a source file anyway, you take the definition of it out of the class and just put it into the anonymous namespace area. That takes some of the implementation detail of your class out of your header file.
If you are working in C++11 use atomic_int rather than int.
Use post-increment operator to make the action properly atomic.
myClass.h
class myClass
{
private:
int id;
public:
myClass();
// etc
};
myClass.cpp
#include <atomic>
#include "myClass.h"
namespace {
static std::atomic_int internalCounter;
}
myClass::myClass()
: id( internalCounter++ )
{
}
the operator++ post-increment on atomic_int is, at the name suggests, atomic, so it will be thread-safe.