Superfluous Matter
Random C++ Fact

I thought I would mention a random C++ programming thinger I came across at work the other day. If you don't work with C++ or don't care about programming you probably want to stop reading now.

Let's say you have a base class, A, which overloads the method "foo" in several ways, like this:

class A
{
public:
    A();
    virtual ~A();

    void foo(int a);
    void foo(int a, int b);
};

Further suppose you have a class B which derives from A, and you'd like to overload "foo" in a new way in the derived class, but also maintain the implementations of the base class A, like this:

class B : public A
{
public:
    B();
    virtual ~B();

    void foo(int a, int b, float c);
};

Due to the way C++ does name resolution, the definition of "foo" in B actually hides the other definitions from A. So if you do this:

B* b = new B();
b->foo(3);

the compiler will fail because it can't find a matching method for foo(int). The problem is that as the compiler walks up the class hierarchy looking for a match for "foo" it will stop at the first class that defines a method with the name "foo" regardless of whether or not there is a suitable match for the specified parameters.

I've actually read about this name resolution rule before, but I never thought about it in this context and so I spent a frustrating half hour trying to figure out why my code wouldn't compile. There are several ways to get around the behaviour. You can redefine the methods of A in B, or you can add a "using" statement to the class definition of B, like this:

class B : public A
{
public:
    B();
    virtual ~B();

    using A::foo;
    void foo(int a, int b, float c);
};

It's important to add the "using" statement before any new definitions of "foo" though.

Anyway, this learning experience turned out to be not immediately applicable because I ended up having to write the code in an entirely different manner anyway. I'm blogging about it so that the experience wasn't a complete loss. Also, this blog post is the first use of the a new feature I just added to my blog to show code in a blog post. Good times!

Previous post | Next post