C++ tip 3: Always initialize C++ objects before you use them.

This is another great tip that I got from the book Effective C++ by Scott Meyers. The author states the following:

Manually initialize objects of built-in type, because C++ only sometimes initializes them itself.

What does this mean? Let me explain.

If you say the following in C++:

int x;

Sometimes x is initialize to zero, but sometimes, it is not. Or lets say that you have a class with the following members:

class Point{
    int x,y;
    };

    Point p;    

The members of p are sometimes initialize to zero but sometimes they are not.

So how do you deal with this problem? The best solution is to always initialize any objects before they are used. For non-member objects of built-in types, you can do it manually:

int x=0;
const char* myName="Harold";

How about for class members? Well, this responsibility falls on the constructor. Here is another great tip from Scott Meyers:

Make sure that all constructors initialize everything in the object.

The keyword here is initialize NOT assign.

For example:

class Point{

        private:
            int x,y;
            std::string name;
            float length;
        public:
            Point(std::string uName, int uX, int uY){
                name=uName;  //These are assignments, 
                x=uX;         //NOT initializations
                y=uY;
                length=0.0;
            }
    }

The constructor above is not initializing its members, it is assigning data to them. It turns out that in C++, data members of an object are initialized before the body of a constructor is entered. So in the class above, the initialization of the members took place before the constructor was called.

So to truly initialize the members, write the constructor with a member initialization list. For example:

class Point{

        private:
            int x,y;
            std::string name;
            float length;

        public:
        //constructor with initialization list
            Point(std::string uName, int uX, int uY):name(uName),x(uX),y(uY),length(0.0){}

    }

Similarly, if you were using a default constructor that doesn't take any parameters, you can initialize the members as shown below:

class Point{

        private:
            int x,y;
            std::string name;
            float length;

        public:
        //constructor with initialization list
            Point():name(),x(),y(),length(0.0){}

    }

So to summarize:

In a constructor, prefer the use of the member initialization list to assignment inside the body of the constructor.

and

Manually initialize objects of built-in type, because C++ only sometimes initializes them itself.

So make sure to apply this rule in your game engine development.

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.