C++: Warning: Derived::f(char) hides Base::f(double)

(quoted from http://www.parashift.com/c++-faq-lite/strange-inheritance.html)


What's the meaning of, Warning: Derived::f(char) hides Base::f(double)? Updated!

[Recently included a new example, changed the parameter types so the behavior seems more bizarre/ominous, and added a note about warnings not being standardized, thanks to Daniel Kabs (in 12/04). Click here to go to the next FAQ in the "chain" of recent changes.]

It means you're going to die.

Here's the mess you're in: if Base declares a member function f(double x), and Derived declares a member function f(char c) (same name but different parameter types and/or constness), then the Base f(double x) is "hidden" rather than "overloaded" or "overridden" (even if the Base f(double x) is virtual).

class Base {
public:
void f(double x);
doesn't matter whether or not this is virtual
};

class Derived : public Base {
public:
void f(char c);
doesn't matter whether or not this is virtual
};

int main()
{
Derived* d = new Derived();
Base* b = d;
b->f(65.3);
okay: passes 65.3 to f(double x)
d->f(65.3);
bizarre: converts 65.3 to a char ('A' if ASCII) and passes it to f(char c); does NOT call f(double x)!!
return 0;
}

Here's how you get out of the mess: Derived must have a using declaration of the hidden member function. For example,

class Base {
public:
void f(double x);
};

class Derived : public Base {
public:
using Base::f;
This un-hides Base::f(double x)
void f(char c);
};

If the using syntax isn't supported by your compiler, redefine the hidden Base member function(s), even if they are non-virtual. Normally this re-definition merely calls the hidden Base member function using the :: syntax. E.g.,

class Derived : public Base {
public:
void f(double x) { Base::f(x); }
The redefinition merely calls Base::f(double x)
void f(char c);
};

Note: the hiding problem also occurs if class Base declares a method f(char).

Note: warnings are not part of the standard, so your compiler may or may not give the above warning.

Comments

Popular posts from this blog

Clearcase check in/uncheck out all the checked out files script

MSSQL GROUP_CONCAT

Duplicating a local copy of project from TFS and making web software client factory to work