Re: Uninitialized data (or here we go again)

Subject: Re: Uninitialized data (or here we go again)
From: Mike Nordell (
Date: Sat Nov 11 2000 - 22:04:22 CST

Michael D. Crawford wrote:
> I think it's important to initialize every member variable of every
> class in the constructor's initializer list

I tend to agree with this, except for the cases where it's impossible or
impractical. In that case the initialization can be deferred to assignment
in the c'tor body, or even not initialized at all until it makes sense to do
so (but these are special cases, for the common case I'd also suggest to
initialize everything).

But never, ever, do what I found just today in AW where a _subclass_
assigned a null value (i.e. trying to "initialize") a _parent class'_ data
member! It was allowed because the parent class' data was not private. The
assignment is now removed, though the data is still not private. I think it
serves as a good example of why there (IMO) is not one single exception to
the rule that all class data shall be private.

> Keep in mind that the C++ compiler will _always_ initialize your members
> using the member's default constructor.

This is only true for non-POD (Plain Old Data, built-in types such as char,
int and so on). PODs are not initialized with the POD type default c'tor
_unless it's explicitly invoked_. Meaning the value of eg an int is not
initialized unless you write it as

    int foo = int();

or in an initializer list as

: foo(int())

where it initializes the POD to zero.

> This may not be the value you
> want, and if you go and initialize it again in the body of the
> constructor, you're initializing it twice which wastes both time and
> code space.

Just to be C++ correct, initialization can only take place once. The second
attempt will result in an assignment. Depending on the complexity of the
assignment operator of that type, the performance impact can be huge.

/Mike - please don't cc

This archive was generated by hypermail 2b25 : Sat Nov 11 2000 - 23:31:22 CST