Linked List Series: C++

So I decided to do C++ for part two. C++ has always been a bit of an interest of mine, because it represents the technical side of programming that you just don’t get out of something like Ruby or Python. I learned C++ while I was studying Computer Science in college and I keep going back to it to challenge myself.

Yesterday’s Ruby Linked list took 28 minutes. Today, the C++ version took around an hour. Technically I worked on it for around an hour and a half and started it twice. Mostly that was me just forgetting how to use C++, but that does speak to the fact that it’s a little more complicated to use as a language and to set up for a project.

I wrote everything into one file last time, but this time I chose to do it how I was taught in college, using header files and implementation files. Each class has a declaration header file, where all variables and functions in the class are declared, and then there is an implementation file that implements the function declarations. You can read about header files vs .cpp files here.

Attention to detail is key in C++, because the error messages are horrible. Watch the video below and you may catch a glimpse of that. I spent 3 hours trying to figure out why I was getting a segfault error one time, and the reason was because when I wrote my class’s constructor, I forgot to initialize some variable to NULL, and when I did things based on if it was NULL or not, weird things started to happen. When variables are declared but not initialized with some value, they are allocated space, but the space is not cleared and filled with anything. So when it comes time to use the variable and read from it’s spot in memory, what you get back is undefined. Not JavaScript’s undefined, but meaning that it literally cannot be defined because there’s no way of predicting what it will be — you’re essentially reading from a random spot in memory. This is called undefined behavior and is a big reason people consider C++ to be a “dangerous language”.

As this guy says:

Undefined behavior comes in 3 flavors:
1) It will kick your dog.
2) It will reformat your hard drive.
3) It will work without a problem.

Use good programming practices, attention to detail and a methodical approach to limit your encounters with it. But then again, that should be standard practice for any language.

You can find the code I wrote here.

You can find the time-lapse of me writing the code here.

Next up: Python.