C++ gotchas

Today I’m going to write about virtual function hiding.

Consider the following code:

#include <stdio.h>

class Foo
{
public:
    virtual void fun(int)
    {
        printf("A");
    }
    virtual void fun(bool)
    {
        printf("B");
        fun(int());
    }
};

class Bar : public Foo
{
public:
    virtual void fun(int)
    {
        printf("C");
    }
};

int main()
{    

    Bar b;
    b.fun(bool());    

    return 0;
}

What will be written to the console?

You will see “C”.

Overloading virtual function fun() in class Bar hides all other versions of functions with that name. Combined with implicit type casting, this may lead to undesirable behaviour.

This is the same problem as you get with multiple inheritance. To fix it, we need to explicitly specify what we want to inherit by adding the following statement to Bar class declaration:
class Bar
{

public:
using Foo::fun;

}

With this statement, output becomes “BC”.

Neither VC++ 8 nor GCC 4 will warn about this. Therefore, regular linting is a must to flush-out bugs like this.

Leave a Reply