[comp.lang.c++] Detecting the first object?

ericr@hpvcfs1.HP.COM (Eric Ross) (08/21/90)

I am creating a set of classes the will access the Network Computing
System (NCS) and a signal handler needs to be initialized exactly one time.

Is there a way for an object to know that it is the first instantiation of
a class?  My gut feel is that there is a way with static members, but I don't
quite have the right recipe.

Thanks,

Eric Ross
Hewlett Packard, Vancouver Division
ericr@vcd.hp.com

dwithers@ncratl.Atlanta.NCR.COM (Dave Witherspoon) (08/21/90)

In article <1120006@hpvcfs1.HP.COM>, ericr@hpvcfs1.HP.COM (Eric Ross) writes:
> I am creating a set of classes the will access the Network Computing
> System (NCS) and a signal handler needs to be initialized exactly one time.
> 
> Is there a way for an object to know that it is the first instantiation of
> a class?  My gut feel is that there is a way with static members, but I don't
> quite have the right recipe.

You're on the right track.  What I have done is provide for a static
class counter, and every trip through the constructor I bump it check
for a value of 1.  Although this seems to be of a "manual" nature, it
works.
-------------------------------David Witherspoon-------------------------------
David.Witherspoon@Atlanta.NCR.COM     | 
NCR E&M Atlanta: (404) 623-7713       |        Visualize Whirled Peas 
MY OPINIONS...ALL MINE!!!             |

ericr@hpvcfs1.HP.COM (Eric Ross) (08/21/90)

I received several responses (next day; talk about results!!).  Here is one
that appears to be in agreement with most of them.  Thanks to all that
responded.

Eric Ross
------------------------------------------
In MyObj.h, say

class MyObj {
private:
	static int numObjs;
	...
public:	MyObj();
	...
}

In MyObj.cc, say

#include "MyObj.h"

int MyObj::numObjs = 0;

MyObj::MyObj() {
	if (numObjs == 0) {
		// I am the first object
		...
	}
	else {
		// I am not the first
	}
	numObjs++;
}


--
Joe Buck
jbuck@galileo.berkeley.edu	 {uunet,ucbvax}!galileo.berkeley.edu!jbuck