C++ tip 4: Use const whenever possible

What does const mean? it simply informs the compiler and other programmers that a variable should not be modified. Reading Efficient C++, I came across a nice tip that I have been trying to implement in my game engine: Use const whenever possible.

Whenever you can, try making your C++ methods const. Why? Take a look at the class below:

class Point{
        private:
              int x,y,z;

        public:
            //method is const
            float calculateDistance(float u) const;

    }

By making the method calculateDistance() a const, it prevents any of the data members: x,y,z to be modified by accident. const informs which method can modify an object and which may not.

This is nice to know, but what If I have a data member which keeps track of distance and needs to be modified by calculateDistance()? In that case you can set the data member as mutable. The keyword mutable frees non-static data members from the constraints of bitwise constness. For example:

class Point{
        private:
              int x,y,z;
            mutable float distance; //May be modified even in const member methods.

        public:
            float calculateDistance(float u) const;

    }    

You can rest assure that the method is not changing data members which should not be modified by the method. Try to incorporate this tip whenever possible in your game engine development.

Harold Serrano

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