I created base class pointer and assigned new derived class to it.
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;
}
Result is:
Base::f(double)
Derived::f(complex)
Base::f(double)
10
Derived::g() 20
Derived::g() 10
Results for b and d are expected. pb->f(1.0) calls Base function f(double), but pb->g() seems to call Derived class function g but using parameter i=10 from Base class. Why?
Baseinterface statically, the dispatch toDerived::pbhappens only at runtime.delete pb;causes undefined behaviour, since Base does not have a virtual destructor