(source: Effective C++, 2E | Item 50 by Scott Meyers)

class Base {
public:
virtual void f(int x);
};
class Derived: public Base {
public:
virtual void f(double *pd);
};
Derived *pd = new Derived;
pd->f(10); // error!

The problem is that Derived::f hides Base::f, even though they take different
parameter types
, so compilers demand that the call to f take a double*, which the literal 10 most certainly is not.

Suppose that when you called f, you really did want to call the version in Derived, but you accidentally used the wrong parameter type. Further suppose that Derived is way down in an inheritance hierarchy and that you were unaware that Derived indirectly inherits from some base class BaseClass, and that BaseClass declares a virtual function f that takes an int. In that case, you would have inadvertently called BaseClass::f, a function you didn't even know existed! This kind of error could occur frequently where large class hierarchies are used, so Stroustrup decided to nip it in the bud by having derived class members hide base class members on a per-name basis.

Note that if not declared with the same agruments in the derived classes, the member functions are not overridden polymorphically, whether or not they are declared virtual.

Note, by the way, that if the writer of Derived wants to allow clients to access Base::f,
this is easily accomplished via a simple using declaration:

class Derived: public Base {
public:
using Base::f; // import Base::f into
                         // Derived's scope
virtual void f(double *pd);
};
Derived *pd = new Derived;
pd->f(10); // fine, calls Base::f

For compilers not yet supporting using declarations, an alternative is to employ an
inline function
:

class Derived: public Base {
public:
virtual void f(int x) { Base::f(x); }
virtual void f(double *pd);
};
Derived *pd = new Derived;
pd->f(10); // fine, calls Derived::f(int),
                  // which calls Base::f(int)
신고
Posted by simon_ryu
TAG


티스토리 툴바