Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!ncar!gatech!bloom-beacon!eru!hagbard!sunic!mcsun!ukc!harrier.ukc.ac.uk!mr3 From: mr3@ukc.ac.uk (M.Rizzo) Newsgroups: comp.lang.c++ Subject: Re: C++ Static Members and Inheritance Keywords: C++ Static Members Inheritance Message-ID: <7510@harrier.ukc.ac.uk> Date: 5 May 91 17:24:06 GMT References: <5069@servax0.essex.ac.uk> Reply-To: mr3@ukc.ac.uk (M.Rizzo) Distribution: all Organization: Computing Lab, University of Kent at Canterbury, UK. Lines: 46 In article <5069@servax0.essex.ac.uk> whisd@essex.ac.uk (Whiteside S D B) writes: >I had a base class in which I declared a static data member. > >I then derived TWO separate classes which both inherited from the base class. > >Then these classes were instanstiated as objects I found that for BOTH the static data member (a pointer) had the SAME value. > >Now I know that a static member is the same for every object of a class, but is the same for every object of a DERIVED class? > >My two objects were not of class "base" but of classes "derived1" and "derived2" respectively. > >I expected each object of Derived1 to have the same data member inherited from base class, and likewise for Derived2, but not that all objects of BOTH classes would have the same. > >I've searched literature high and low for an answer to this. Nowhere do they mention what happens when you inherit a static member (data or function). > >Any suggestions or corrections welcome. I've experienced this problem before. The only solution I found was to re-declare the static data members in every subclass I needed them. However this should be done with care. If a base class member function refers to a static data member, then if this function is inherited by a derived class re-declaring the same static member, the base class static member will still be the one referenced by the inherited function. What we need here is virtual static data members ! Unfortunately there are no such thingies :-( To solve this problem you can define two virtual non-static functions to read and write the member - though again this must be done for every derived class where the static member is declared. Macros are very handy here ! Does anybody know of another (possibly better) approach ? Also, a suggestion - why not consider adding virtual static data members to the language defintion ? (No I haven't got it wrong - I know ``virtual'' is normally associated with functions) I think they could be useful as described in the above case. The need to have derived classes with _their own_ static data often arises e.g. to store an instance count. >Simon Whiteside Michael Rizzo