본문 바로가기

IT

Virtual function with parameter types different from those of a base class

(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)

'IT' 카테고리의 다른 글

R  (0) 2014.07.02
Maple 강의자료  (0) 2009.04.10
국내 아키텍트 평균 연봉은 6450만원  (0) 2009.02.17
Friend functions and classes  (0) 2008.09.03
Copy constructor and assignment operator of derived class  (2) 2008.07.28