[gnu.g++] static data members and derived classes

gas@cs.nott.ac.uk (Alan Shepherd) (05/31/90)

I apologize if I'm asking a lot of banal questions, but no-one seems
to answer !  I'd rather have 60 answers than none at all.

I would like the position regarding static members and derived classes
clarified.  Consider a class 'a' with a protected static int 'number':

class a
{
	protected:
		static int number;
}

Now derive a class `b' from 'a':

class b: public a
{
}

From my understanding of the AT&T reference manual for release 2.0
($11.5), I should now be able to refer to b::number.  Unfortunately,
cfront complains that b doesn't have a member 'number'.  This doesn't
appear to make sense.  However, g++ compiles fine, but does something
even more peculiar.

int a::fred =3;
int b::fred =4;

The above two statements leave both a and b with the value 3 for fred.
However, during normal execution (i.e. after main) changing the value
of a::fred or b::fred sets them both to be the same value.  This means
that there is definitely a bug in the way g++ initialises the static
members before main and the policy seems odd.  I would rather have
class 'b' inherit its own distinct static member.

Alan Shepherd

bs@alice.UUCP (Bjarne Stroustrup) (06/01/90)

Alan Shepherd (Computer Science, Nottingham Univ., UK.) writes:

 > I apologize if I'm asking a lot of banal questions, but no-one seems
 > to answer !  I'd rather have 60 answers than none at all.


This one at least is in no way banal.

 > I would like the position regarding static members and derived classes
 > clarified.  Consider a class 'a' with a protected static int 'number':
 > 
 > class a
 > {
 > 	protected:
 > 		static int number;
 > }

 > Now derive a class `b' from 'a':

 > class b: public a
 > {
 > }

 > From my understanding of the AT&T reference manual for release 2.0
 > ($11.5), I should now be able to refer to b::number.  Unfortunately,
 > cfront complains that b doesn't have a member 'number'.  This doesn't
 > appear to make sense. ...

I would like to make an appeal to the effect that when people post a note
pointing out a bug in a compiler (any compiler) that they actually enclose
a small program that exhibit the problem. The example above doesn't qualify.

This cleaned up version does - and doesn't exhibit the problem:


	class a
	{
		public:// protected:
		static int number;
		f();
	};

	class b: public a
	{
	};

	f()
	{
		b::number = 7;
	}


That is, b::number is correctly resolved to a::number. I used cfront 2.0.
The problem comes when you use b::number in the declaration of a::number.
In that case cfront insists on the exact name:

	int b::number = 7;	// error
	int a::number = 8;	// ok

I think that is reasonable. Similarly

	b::f() { /* ... */ }	// error
	a::f() { /* ... */ }	// ok

The scope rules that allows access to a base class member when qualified
by the name of a derived class are stated for uses only not for definitions.