Item 21. Overriding Virtual
Functions
Difficulty: 6
Virtual functions are
a pretty basic feature, but they occasionally harbor subtleties
that trap the unwary. If you can answer questions like this one,
then you know virtual functions cold, and you're less likely to
waste a lot of time debugging problems like the ones illustrated
below.
In your travels through the dusty corners of
your company's code archives, you come across the following program
fragment written by an unknown programmer. The programmer seems to
have been experimenting to see how some C++ features work. What did
the programmer probably expect the program to print, and what is
the actual result?
#include <iostream>
#include <complex>
using namespace std;
class Base
{
public:
virtual void f( int );
virtual void f( double );
virtual void g( int i = 10 );
};
void Base::f( int )
{
cout << "Base::f(int)" << endl;
}
void Base::f( double )
{
cout << "Base::f(double)" << endl;
}
void Base::g( int i )
{
cout << i << endl;
}
class Derived: public Base
{
public:
void f( complex<double> );
void g( int i = 20 );
};
void Derived::f( complex<double> )
{
cout << "Derived::f(complex)" << endl;
}
void Derived::g( int i )
{
cout << "Derived::g() " << i << endl;
}
void main()
{
Base b;
Derived d;
Base* pb = new Derived;
b.f(1.0);
d.f(1.0);
pb->f(1.0);
b.g();
d.g();
pb->g();
delete pb;
}
|