home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!usc!cs.utexas.edu!qt.cs.utexas.edu!yale.edu!newsserver.jvnc.net!newsserver.technet.sg!nuscc!papaya!suresh
- From: suresh@papaya.iss.nus.sg (Suresh Thennarangam - Research Scholar)
- Subject: Re: Need access to array index in ctor
- Message-ID: <1993Jan23.050800.20254@nuscc.nus.sg>
- Sender: usenet@nuscc.nus.sg
- Organization: Institute Of Systems Science, NUS
- References: <C1A1nx.K2L@undergrad.math.waterloo.edu>
- Date: Sat, 23 Jan 1993 05:08:00 GMT
- Lines: 47
-
- In article <C1A1nx.K2L@undergrad.math.waterloo.edu> wgsteven@mobius10.math.uwaterloo.ca (Warren Stevens) writes:
- >I am creating a class, called block, that needs to know it's index in a
- >constructor if it is created as part of an array. For instance,
- >
- > House block[512];
- >
- >would call block::block() 512 times. Each time the constructor is called,
- >i need to know what the index being created is.
- >
- >Is there some way to do this easily?
- >
- >Thanks,
- >
- >Warren
-
- Off the top of my head ( no flames please :->) here's a simple hack ...
-
- Define a static member variable in the class, set it to zero and increment
- it in the constructor .. a kind of class instance counter (this group has
- seen a major discussion on class instance counting so I'm not going to
- restart the same thread )
-
- Within the constructor, the value of the static counter variable index will
- give you the index of the instance being instantiated.
-
- Assumptions:
- 1> No other instances (besides the array)have already been created.
- 2> The constructors for an array of classes declaration are called in order
- of increasing index( Can this be guranteed ? Anyone ?). A simple way to
- verify if this is happening will be to print out the value of
- (this - counter). It should be the same each time .. i.e the address of the
- zero'th variable of the array.
-
-
- __
- (_ / / o_ o o |_
- __)/(_( __) (_(_ /_)| )_
-
-
- ***************************************************************************
- * Suresh Thennarangam * EMail: suresh@iss.nus.sg(Internet) *
- * Research Scholar * ISSST@NUSVM.BITNET *
- * Institute Of Systems Science * Tel: (065) 772 2588. *
- * National University Of Singapore * Facs.: (065) 778 2571 *
- * Heng Mui Keng Terrace * Telex: ISSNUS RS 39988 *
- * Singapore 0511. * *
- ***************************************************************************
-