[comp.lang.c++] explicit member initialization

grunwald@m.cs.uiuc.edu (11/04/88)

One of the disappointing complexities of C++ is that you don't get very
much control when initializing members that are class instances, as well
as the previously mentioned problem of specifying the ordering of
global member initializations.

Certainly, you can say:

Foo::Foo(int x, char y) : instance(x,y), another(x*y)

and the like, but realistically, there's no reason you couldn't delay the
creation of an instance and the call to the constructor.

In certain cases, this can be invaluable, e.g., you need to compute something
before initializing a member. As it is, you have two choices:
create it using ``new'' or have some way to ``reset'' a class.

E.g., I have a class MLCG that implements a random number generator, and
I have a subclass of Thread allocates a random number generator based on
the ID number of the thread. The thread needs to reserve a global lock,
grab a counter, release the lock and then initialize the MLCG instance.

Right now, I have two options:
	(1) have the parent of a thread compute the information
	(2) ``initialize'' the MLCG structure twice, once using a
	    default and once using the values I want.

Option (1) is fine, except that you wind up passing a lot of information
to threads that maybe you don't care about. Also, you need to pass it
from the point you say ``new Thread'', which is the wrong place to compute
such Thread-specific information. Also, it's faster to have
10 CPUs executing threads that are initializing themselves than to have
1 CPU executing a thread that initializes everyone else.

With data-flow information from the compiler, you can certainly issue
warnings like ``use of XYZ before constructor called'', or better yet,
just force a call to the constructor at that point. The only problem
is that there isn't a syntactic mechanism for this.