Pulling functions into scope

Don’t you hate it when you remember that you’ve done something, but it just slips your mind as to how you did it? Happened to me, so I figured I would blog it so I don’t waste 20 minutes next time finding out what I did.

Scenario

You have a parent class which defines a function (lets call it func), and it overrides it multiple times with a variety of parameters. So we have (for example) 3 forms of it. We also happen to have a derived class which uses a virtual override for one of the forms.

Problem

If you have a pointer to the derived class, and you call one of the func’s which is on the base class but not overridden on the derived class, then the compiler will complain. If the compiler sees at least one definition for func in the derived class, then it expects to find the form you’re calling to also be defined in the derived class.

Solution

You want the compiler to say “okay I found one definition for func, but its not the one I want, so I will look in the base class”. The only way to do this is to pull the definitions from func through from the base class into the derived class. Using the ‘using‘ keyword!

Example Code (with poor formatting – this blog needs code formatting tags)

class P1
{
public
:
void func() { cout << 1; }
void func( int x ) { cout << x; }
};

class C1 : public P1
{
public
:
using P1::func; // we bring the func()’s from the base class into scope here
void func() { cout << 2; }
};

int _tmain(int argc, _TCHAR* argv[])
{
C1 c;
c.func();
c.func(5); // note how this function will call the base class’ version
return 0;
}


About this entry