Newsgroups: comp.lang.c++
Path: utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!geac!alias!rae
From: rae@alias.com (Reid Ellis)
Subject: Re: Constructor question
Message-ID: <1991Apr7.071322.11828@alias.com>
Sender: news@alias.com (USENET News)
Organization: Alias Research, Inc. Toronto ON Canada
References: <1991Apr2.110623.22219@and.cs.liv.ac.uk> <fuchs.670695206@t500e0> <1991Apr5.035053.27973@mathcs.sjsu.edu>
Date: Sun, 7 Apr 91 07:13:22 GMT

Harald Fuchs <fuchs@t500e0.telematik.informatik.uni-karlsruhe.de> writes:
>When I have to do lots of
>common initialization, I put it into a private member function
>(e.g. void init ();) and call this function from the constructors.
>Unfortunately, this won't work if you have to initialize constant or
>reference data members. IMHO a hole in the language.

Not really a hole.  As pointed out, you have to do some repetition
sometimes.  But even this can be cut down, although in a way that I
think violates the spirit of initializers:
----
#include <stream.h>

struct X {
	X();

	int init_all();

	int a;
	char str[80];
	float f;
	int &aRef;
};

X::X() : a(init_all()), aRef(a)
{
}

int X::init_all()
{
	static int count = 1;

	sprintf(str, "This is test #%d", count++);
	f = 1.23;
	return 23;
}

int main()
{
	X anX;
	const X constX;

	cout << form("   anX = {%d, \"%s\", %g, %d}\n",
			anX.a, anX.str, anX.f, anX.aRef);
	cout << form("constX = {%d, \"%s\", %g, %d}\n",
			constX.a, constX.str, constX.f, constX.aRef);
	return 0;
}
----
When run, you should get something like:

	   anX = {23, "This is test #1", 1.23, 23}
	constX = {23, "This is test #2", 1.23, 23}

Note that
	a) this works even for const objects, unlike the generic init()
	b) you still have to initialize references normally

						Reid
--
Reid Ellis     1 Trefan Street Apt. E, Toronto ON, M5A 3A9
rae@utcs.toronto.edu        ||  rae%alias@csri.toronto.edu
CDA0610@applelink.apple.com ||      +1 416 362 9181 [work]
