Re: How to define and initialize the protected static members ?
Timothy Madden <terminatorul@gmail.com> wrote:
blargg wrote:
[...]
My error was on a line further down. My code is:
using namespace std;
extern
class SystemName
{
public:
string sys_name;
protected:
SystemName(string sys_name)
: sys_name(sys_name)
{
}
static SystemName sys_type;
}
&systype;
SystemName SystemName::sys_type("basicplatform");
SystemName &systype = SystemName::sys_type;
I am trying to write a single-ton class, that can only be accessed
through a reference, SystemName &systype, instead of a function
like SystemName &SystemName::getInstance(), which is ugly.
The real code is at work and is for a class that exposes
application-global settings as public data members initialized
from the application's configuration file. I think a single-ton
class is appropriate for such a case, and I want the users of
the configuration class to be able to access just the reference.
The error is obviously on the last line where the reference is
initialized with the protected member, but still in the compiler
output messages the first error is listed at the previous line,
with the definition of the static member, making me believe the
compiler could not define the protected static member.
I do not know why g++ reports the error as if on a previous line,
even in version 4.2.4
I just tried (with the addition of #include <string>) and sure enough, I
get this error:
test.cpp:17: error: "SystemName SystemName::sys_type" is protected
test.cpp:19: error: within this context
Line 17 is the definition of sys_type, and line 19 is where you try to
make a reference to it. The compiler could have given us the context
within the class definition, rather than the definition, but it's clear
enough to find the error. If I remove the definition of sys_type, it gives
a better context reference to the "static SystemName sys_type" line in the
class definition:
test.cpp:13: error: "SystemName SystemName::sys_type" is protected
test.cpp:19: error: within this context
Objects/references to SystemName don't get special access to
protected/private members in their initializers, so you'll have to find
another way to expose sys_type. BTW, practice writing minimal test code,
as it will greatly increase the chances of people here reading your post
and spending time solving it. The following is a better test case for the
problem you had:
class Foo {
protected:
static Foo instance;
};
Foo Foo::instance;
Foo& foo = Foo::instance;
int main() { }
/*
$ g++ test.cpp
test.cpp:6: error: 'Foo Foo::foo' is protected
test.cpp:8: error: within this context
*/