Re: Uninitialized data (or here we go again)


Subject: Re: Uninitialized data (or here we go again)
From: Michael D. Crawford (crawford@goingware.com)
Date: Sat Nov 11 2000 - 16:57:04 CST


I think it's important to initialize every member variable of every
class in the constructor's initializer list. Do this in the same order
that the members are declared in the class declaration in the header
file, like this:

class Foo{
        public:
                Foo();
        private:
                long mAMember;
                long mAnotherMember;
};

Foo::Foo()
        : mAMember( 1 ),
                mAnotherMember( mAMember * 2 )
{}

Keep in mind that the C++ compiler will _always_ initialize your members
using the member's default constructor. 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.

Also note that the compiler will _always_ run through the initialization
list - whether you've explicitly placed items in there or not - in the
same order as they're declared in the class declaration, so it only
makes sense to put them in the initializer list in the same order. Also
note that this guaranteed order allows you to use an earlier member as a
parameter to the constructor of a later member.

Finally, don't call member functions of the currently-being-constructed
class from the initializer list (because it is not completely
constructed). If you need to write a subroutine to calculate a
parameter for an initializer, declare it static and pass it all the
parameters it needs explicitly. Also don't pass "this" to any other
subroutine from the initializer list, again because the class is not
completely constructed - the exception to this is that you can pass
"this" to a routine that's expecting a pointer to your base class,
because the base class _has_ been completely constructed.

Mike

-- 
Michael D. Crawford
GoingWare Inc. - Expert Software Development and Consulting
http://www.goingware.com
crawford@goingware.com

Tilting at Windmills for a Better Tomorrow.



This archive was generated by hypermail 2b25 : Sat Nov 11 2000 - 18:55:45 CST