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

Outlook : "operation failed, object could not be found. " when trying to close a PST.

How to transfer app and data from old iPhone to new iPhone for model IOS17 and IOS18 above.

Tips on how to use IBM iNotes (web client) on emailing or scheduling - Like copy tables from Excel or checking for user id (windows logon id) through email address