Who`s Afraid to Be Const Correct? Help Your Compiler Help You - Why Use the Compiler to Catch Errors?
(Page 3 of 4 )
It would be wonderful if you were able to write bug-free code 100% of the time, but I don’t know any programmers who can (maybe I just hang out with the wrong people
). Even though compiler errors can lead you in the wrong direction, they will still point you to the location where there is a problem with your code. These days I just take note of the line number mentioned in the error message and try to see if I can find the problem on my own. Only when I have problems spotting the error, do I look at what the compiler thought was wrong with it. You could say this is my conditioned response after having too many fits with the compiler pointing me in the obvious wrong direction.
Scripts are great when you need quick mockups or tools, and I use Python and Lua a lot. But because they are weakly typed, errors that would have been caught by a C++ compiler go unnoticed by their weakly typed script compilers/interpreters. To discover a bug during runtime while trying to demonstrate something to your manager is rather painful. Somehow this seems to happen a lot. Everything works fine until somebody asks you to do a demonstration.
It is much better to find errors during compile time than it is to find them during run time. Since you can run a program many times without touching all the code, it is possible for a run time bug to surface only at a late stage; compile time bugs are found every time you compile.
Constant member functions are a good example of coding contracts that enable the compiler to find inconsistencies in your design and/or implementation. This is one of the reasons that it can be so painful to introduce const at a late stage of a project… it makes it clear that pieces of code are being used the wrong way.
Maybe it wasn’t visible that the contracts were being broken, and maybe the application appears to be working fine. Still I can guarantee that if you continue without making it const correct, damage will be done for real at some point. And finding the root of the bug will be very difficult at that time.
So take a closer look at code that uses const_cast to remove const from variables or parameters. Whoever decided to use the const_cast wanted to work around an error the compiler would otherwise spit out. He is trying to work around a contract that he clearly is violating!
It is always very interesting to see which coders are ignoring compiler warnings.
Next: Conclusion >>
More C++ Articles
More By J. Nakamura