warsaw@nlm.nih.gov (Barry A. Warsaw) (12/05/90)
I have a question about scope and access permissions in the
initialization of static class members. In the code following my
siggy, I've got a program with 2 classes: first and second. Class
second contains a static data member of type first, which is
initialized on the line:
first second::one = ( 9 );
Now, if the constructor for class first is public, everything compiles
and works fine. However, if the constructor is protected, the
compiler complains with:
error: ..() cannot access first::first(): protected member
even though class second is made a friend of class first (which
*should* give it access to first's protected members, right?). Unless
this is a bug in the compiler, I obviously have a misunderstanding
about scope and access in this situation. Is the error because this
initialization is being done at file scope, which doesn't have access
to first's protected member? I haven't been able to find a definitive
answer in the books I've read. Forget, for the moment, why I'd want
to have a protected constructor for class first.
For the record I'm using Sun's C++ (CC -v produces: Sun C++ 2.0 FCS -
10/20/89), on an SS1+. Compile the following program as is to produce
the error, or with -DPROTECT=public to eliminate the error.
Could someone please explain exactly what the problem is, and how to
correct it while still keeping first's constructor protected? Or tell
me why it *must* be public for this to have meaning. Thanks for your
help.
-Barry
NAME: Barry A. Warsaw INET: warsaw@nlm.nih.gov
TELE: (301) 496-1936 UUCP: uunet!nlm.nih.gov!warsaw
======================================================================
#include <stream.h>
#ifndef PROTECT
#define PROTECT protected
#endif
class first {
friend class second;
int cnt;
PROTECT:
first( int c=1 ) { cnt = c; }
public:
int count() { return( cnt ); }
};
class second {
static first one;
int cnt;
public:
second() { cnt = 1; }
int count() { return( one.count() ); }
};
first second::one = ( 9 );
main() {
second foo;
cout << "foo: " << foo.count() << "\n";
};