Topic: Why's of C++ -- Part 3: Structured programming with constructors


Author: "Anders J. Munch" <andersjm@dancontrol.dk>
Date: 1999/08/20
Raw View
Al Stevens wrote in message ...
>>class X {
>>public:
>>    const int i1, i2, i3, i4 /*etc*/, i22;
>>    X(int a1, float a2, float a3, V *);
>>    // the following is what I would like to do
>>    X(void) : X(0,0.,10.,NULL) {}
>>};
>>I have found ways around this limitation; but, I was wondering if anyone
>>could explain the rationale behind disallowing it.
>
>I can guess, although you might not like it. It's probably like the null
>declarator you mentioned in another thread: It wasn't disallowed. It was
>never allowed. There's a difference.

In a sense it *was* disallowed with the invention of a kind of function that
could only be invoked under special circumstances using special syntax:  The
constructor.  Some of the later additions to the language are in reality bug
fixes introduced to amend this, e.g. placement new.  If a constructor was
just a regular method that would happen to be called during object
construction, noone would ever need a special placement new syntax.

> What is permitted in the ctor
>initialization list is not a function of all the things that are not
>permitted. They allowed what they felt was required.
>
>Necessity being the mother of invention, no one thought to allow that
>because no one had a need.
[..]

Actually my count of people who at one time or another though they had a
need comes to at least three people so far: Greg Brewer, you (Al Stevens)
and me.  Like you I figured out the workarounds, and then I forgot all about
it.

IMHO having one constructor call another is a natural,
structured-programming kinda thing to do.  Often you have a default
constructor that creates the basic integrity of the object, such as
initializing those members that all methods assume to be well-defined, and
others that do that and "some more".

The workaround where different constructors call the same Init() method
doesn't work with reference members nor with base class initialization.
Exactly the parts you need to share the most!

blargg's workaround with an extra base class is a more general solution, but
the added complexity kinda defeats the purpose.

- Anders




[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]