Article View: borland.public.cppbuilder.oodesign
Article #3Re: Counting the number of instances of a user defined class
From: Remy Lebeau (TeamB)
Date: Tue, 08 Jul 2003 06:58
Date: Tue, 08 Jul 2003 06:58
53 lines
2515 bytes
2515 bytes
"Pang Fu" <nospam_pangfu@hotmail.com> wrote in message
news:3f0a59ff@newsgroups.borland.com...
> How to count how many instances are created
> of a user defined class?
Add a static member to the class, then increment it in the constructor and
decrement it in the destructor.
> In the following example how TMyClass can count
> the number of instances (objects created from TMyClass) ?
> InstanceCount ++; <--?? How to start from zero and increment?
Static members must be defined separately from the class declaration.
Simply declare the variable to have an initial value of 0 when you define it
in your source file:
--- header file ---
class TMyClass
{
public :
// InstanceCount must be public if you intend to access it directly
otherwise
// you will need to declare a public method to return the value
instead
static int InstanceCount;
TMyClass() { ++InstanceCount; }
~TMyClass() { --InstanceCount; }
};
--- source file ---
int TMyClass::InstanceCount = 0;
> const int N= 456;
> for (int i=0; i<N; i++){
> TMyClass *MyObj = new TMyClass();
> }
You do realize that you have a memory leak there, don't you? You are
allocating 456 instances of the class dynamically, but are never freeing
them.
> AnsiString S;
> S.sprintf("Instance Count :%d", ????How????);
S.sprintf("Instance Count :%d", TMyClass::InstanceCount);
Gambit
Technical Details
Message-ID:
<3f0a6a97$2@newsgroups.borland.com>Path:
arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-06!sn-xit-08!supernews.com!newsfeed.wirehub.nl!news.kweb.on.ca!newsgroups.borland.com!not-for-mailReferences:
<3f0a59ff@newsgroups.borland.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 102541,bcc8bd10d54dd071 X-Google-Attributes: gid102541,public X-Google-Thread: 10db1e,bcc8bd10d54dd071 X-Google-Attributes: gid10db1e,public X-Google-ArrivalTime: 2003-07-08 00:02:48 PST From: "Remy Lebeau \(TeamB\)" <gambit47@yahoo.com> Newsgroups: borland.public.cppbuilder.oodesign,borland.public.cppbuilder.students References: <3f0a59ff@newsgroups.borland.com> Subject: Re: Counting the number of instances of a user defined class Date: Mon, 7 Jul 2003 23:58:57 -0700 Lines: 56 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2800.1158 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106 NNTP-Posting-Host: 207.175.226.26 Message-ID: <3f0a6a97$2@newsgroups.borland.com> X-Trace: newsgroups.borland.com 1057647255 207.175.226.26 (7 Jul 2003 23:54:15 -0700) Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-06!sn-xit-08!supernews.com!newsfeed.wirehub.nl!news.kweb.on.ca!newsgroups.borland.com!not-for-mail