home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- From: nikki@trmphrst.demon.co.uk (Nikki Locke)
- Path: sparky!uunet!pipex!demon!trmphrst.demon.co.uk!nikki
- Subject: Re: static "inheritance" question
- Reply-To: nikki@trmphrst.demon.co.uk
- References: <1993Jan4.144320.5586@dayfac.cdc.com>
- Distribution: world
- X-Mailer: cppnews $Revision: 1.30 $
- Organization: Trumphurst Ltd.
- Lines: 76
- Date: Wed, 6 Jan 1993 12:09:22 +0000
- Message-ID: <726347362snx@trmphrst.demon.co.uk>
- Sender: usenet@demon.co.uk
-
- In article <1993Jan4.144320.5586@dayfac.cdc.com> pault@dayfac.cdc.com (Paul Thompson;DAYFAC-ITS;) writes:
- > Consider class A which counts its 'live' instantiations.
- >
- > class A {
- > static int nr;
- > public:
- > A() {nr++;}
- > ~A() {nr--;}
- > int getNrInstances () {return nr;}
- > };
- > ...
- > A::nr = 0;
- >
- > A has useful functionality which I would like to use in other
- > classes with MINIMAL change to the other classes. One way
- > is to try:
- >
- > class B :public A { ....};
- > class C :public A { ....};
- > ...
- > B b1, b2, b3;
- > C c1, c2;
- > cout << B::getNrInstances();
- >
- > But this doesnUt work because static variables aren't inherited
- > (at least not in my compiler).
-
- This DOES work, but perhaps not in the way you intended. It counts how
- many objects of type A are created. I.e. the total of all A's, B's and C's
- together.
-
- > Could anyone enlighten me as to how to acquire the functionality
- > of a class like A that depends on a static variable with LEAST
- > modification to the acquiring class ? Thanks.
-
- I would suggest that A is turned into a template class. I compiled and
- tested the following under Borland C++ ...
-
- #include <iostream.h>
-
- template <class X> class Counted {
- static int nr;
- public:
- Counted() {nr++;}
- Counted(const Counted ©) { nr++; } // You NEED this !
- ~Counted() {nr--;}
- static int getNrInstances () {return nr;} // Note static !
- };
-
- class A : public Counted<A> {
- };
- int Counted<A>::nr = 0;
-
- class B : public Counted<B> {
- };
- int Counted<B>::nr = 0;
-
- class C : public Counted<C> {
- };
- int Counted<C>::nr = 0;
-
- main()
- {
- A a1, a2, a3;
- B b1, b2;
- C c1;
-
- cout << " A:" << A::getNrInstances();
- cout << " B:" << B::getNrInstances();
- cout << " C:" << C::getNrInstances();
- return 0;
- }
-
- --
- Nikki Locke,Trumphurst Ltd.(PC and Unix consultancy) nikki@trmphrst.demon.co.uk
- trmphrst.demon.co.uk is NOT affiliated with ANY other sites at demon.co.uk.
-