Home > Uncategorized > Amusing mistakes in C++

Amusing mistakes in C++

I was writing some complicated inherited classes in C++, and made a few amusing mistakes, which resulted in some strange errors.

Firstly, the concept of method hiding is when you declare a method with the same name of a method that exists in a parent class. This doesn’t override the method (unless it was marked as virtual), but any calls to that method will go to the method defined in the child class. This can lead to really strange results if you were expecting a method override, but forgot to put virtual in the parent class, as I did.

class Parent
{
   public:
        void foo();
};

class Child
{
    public:
        void foo();
};

Now mistakes like this are obvious in small classes, but in large classes, while on six hours sleep, they can be harder to pinpoint.

The other mistake was when I didn’t realize I already had a protected method, we’ll call it bar, declared in the parent class. I then defined a private method called bar in the child class, in which I was trying to call the parent class. Guess what? Infinite recursion.

Lesson of the day? Don’t code while tired. It doesn’t work very well.

Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.