I'm new to OOP and trying to create a singleton that requires extensive initialization. I am declaring the private constructor in the header file and trying to define that constructor in a separate .cpp file.
Dev-Cpp (using gcc) complains that the private attributes I'm trying to initialize and the constructor are private, i.e., not visible.
Does C++ require private functions to be defined when they're declared, or is there something I'm overlooking in using private methods? I'm guessing that my mistake is transparently obvious, but I've included the files and error log after my sig if you need to see how I'm screwing up.
Compiler: Default compiler
Executing g++.exe...
g++.exe "C:\Dev-Cpp\Random\random.cpp" -o "C:\Dev-Cpp\Random\random.exe"
C:\Dev-Cpp\Random\/random.h: In function `PRNG_Class* instance()':
C:\Dev-Cpp\Random\/random.h:19: error: `PRNG_Class*PRNG_Class::only_instance_s' is private C:\Dev-Cpp\Random\random.cpp:28: error: within this context
C:\Dev-Cpp\Random\/random.h:19: error: `PRNG_Class*PRNG_Class::only_instance_s' is private
C:\Dev-Cpp\Random\random.cpp:30: error: within this context
C:\Dev-Cpp\Random\/random.h:20: error: `PRNG_Class::PRNG_Class()' is private
C:\Dev-Cpp\Random\random.cpp:30: error: within this context
C:\Dev-Cpp\Random\/random.h:19: error: `PRNG_Class*PRNG_Class::only_instance_s' is private
C:\Dev-Cpp\Random\random.cpp:31: error: within this context
C:\Dev-Cpp\Random\/random.h:18: error: `int PRNG_Class::value_m' is private
C:\Dev-Cpp\Random\random.cpp:31: error: within this context
C:\Dev-Cpp\Random\/random.h:19: error: `PRNG_Class*PRNG_Class::only_instance_s' is private C:\Dev-Cpp\Random\random.cpp:33: error: within this context Execution terminated
int PRNG_Class::get_value()
{
return PRNG_Class::only_instance_s->value_m;
}
void PRNG_Class::set_value(int v)
{
PRNG_Class::only_instance_s->value_m = v;
}
// don't use static here
// Qualify the function name with the class name
PRNG_Class* PRNG_Class::instance()
{
if(!PRNG_Class::only_instance_s)
{
PRNG_Class::only_instance_s = new PRNG_Class;
PRNG_Class::only_instance_s->value_m = 0;
};
return PRNG_Class::only_instance_s;
}
// Actually define the static variables
PRNG_Class * PRNG_Class::only_instance_s;
Thanks for spotting the incorrect qualification; I imagine that when I get home, it'll make a world of difference.
It makes sense to put the static variables in the .cpp file rather than the .h file. Why do so many examples put them in the private section of the header?
Also, thanks for the tip on using new-style headers vs. the old c-style ones.