An nice C++ quiz floated to the top of HackerNews earlier this week. I don't think it's too hard for people who have been programming in C++ for a while, but it illustrates why C++ is so frustrating at times.

My favorite example of this so far has been this simple exception question. The intention of the programmer of this snippet is probably to catch the root of a hierarchy of exceptions and get some specific information about the exception recorded. The program should be straightforward, but as the answer illustrates, the difference between this program and the correct program is exactly one character:

We throw a SpecialException. It is derived from GeneralException, but is caught by value, so e will have the dynamic type GeneralException, not SpecialException. This is known as slicing.

Instead, we should have caught it by reference catch (GeneralException& e), then its dynamic type would be SpecialException, and the program would output S.

C++ is full of pitfalls like this. Most of them strike you as absurd until you think about it for a while from the perspective of having to make a compiler for this language. Once you do that, they make... well, they have a certain logic, they nag in the back of your brain, and make you glad that Scott Meyers has already written down a lot of the annoying cases that come up commonly.

Of course, the most frustrating thing about C++'s pitfalls is that it's such a large language that many people react to gotcha moments like the ones in the quiz by saying "nobody writes code like that". And it's true, most of the time you don't write code like quiz code. But you do get to see errors from programmers being surprised about const interacting with template generation, forgetting the details of initialization order, or being confused about what happens when a constructor throws an exception1. This quiz code might be simple or obviously2 wrong, but it's fairly certain that in any large C++ project you will find a couple examples of well-intentioned code that is unfortunately completely wrong.


  1. To be fair, I think it's completely valid to call this a problem that many people don't have, since many folks ban exceptions in their style guides or can't use exceptions due to hard real-time performance constraints. 

  2. Someday someone will figure out how to constrain programmers to committing only obviously wrong mistakes and I will rejoice. 

Jamie Culpon (自映実*クルポン)

Jamie is a non-binary games developer and (recovering) network operations programmer/engineer.

Jamie Culpon (自映実*クルポン)