Initializing Non-pointer Class Members

4.4k views Asked by At

Lately, I've been reading much about constructors from the well-received C++ FAQ. One of entries mentions that it's always best to use initialization lists, as opposed to initializing class members within the code-block of the constructor itself.

This is because the compiler tends to create multiple copies of the class members, rather than simply one copy.

Example

Good

Foo::Foo( void )
    : mBar( new Bar ) //pointer to some memory address
{
}

Bad

Foo::Foo( void )
{
    mBar = new Bar;
}

One thing it also states (and, while this relates to constructors, it also relates to pure initialization of objects in general from even non-member functions ) is that when initializing an object through methods such as the following:

void f( void )
{
    Foo foo( Bar() ); //Bad.

    foo.x(); //error
}

You will, and I quote: "[declare] a non-member function that returns a Foo object".

(for more info, click the link above)

The Question

Because of this, is it unwise to have the following:

Geometry::Geometry( void )
    : mFaces( QVector< GLushort >() ),
      mFinalized( false ),
      mNormals( QVector< QVector3D >() ),
      mVerticies( QVector< QVector3D >() )

Or even this:

Geometry::Geometry( void )
    : mFaces( QVector< GLushort > ),
      mFinalized( false ),
      mNormals( QVector< QVector3D > ),
      mVerticies( QVector< QVector3D > )

Because of the way that these are allocated (i.e., the fact that these are non-pointers), it makes me wonder whether or not these objects even NEED initialization in the beginning. If they do, is this the correct method of going about it? Or, is there a better method of initialization?

How this relates to the question

This relates to the general question due to the way that the methodology behind C++ constructor initialization relates to both initializing objects using constructor functions, along with the fact that I am ignorant to whether or not objects allocated on the stack - or, so I believe anyway - (either way, objects without pointer allocation) even need initialization in the first place.

1

There are 1 answers

2
James McNellis On BEST ANSWER

If a member variable is of a class type with a user-declared default constructor, you do not need to explicitly mention it in the initialization list: its default constructor will be called anyway, during construction, before the body of the constructor is entered.

If a member variable is a primitive type (like int or bool) or is of a class type that doesn't have any user-declared constructors, you need to initialize it explicitly, otherwise it will not be initialized (and it will have an unknown value; you cannot read an uninitialized object).