#include <iostream>
class base
{
public:
virtual void print (int a)
{
std::cout << "a: " << a << " base\n";
}
virtual void print (int a, int b)
{
std::cout << "base\n";
}
};
class derived : public base
{
public:
virtual void print (double d)
{
std::cout << "derived\n";
}
};
int main ()
{
int i = 10;
double d = 10000.0;
base *b = new derived ();
b->print (i, i);
b->print (d);
return 0;
}
The output of this function is:
base
a: 10000 base
- Why
b->print (d)don’t invoke the derived class implementation and
performs static cast on'd'to provide a match with base class
implementation ? - What rule is applied here during virtual function lookup ?
derived::printdoes not override any member function inbase. It is declared as having a single parameter of typedoublebut the two virtual member functions namedprintinbaseare declared as having one and two parameters of typeint.When you use
b->print(d), only member functions inbaseare considered during overload resolution, so onlyvoid base::print(int)andvoid base::print(int, int)are considered.void derived::print(double)can’t be found because the compiler has no idea thatbpoints to aderivedobject.If
derivedwere to override one of the twoprintfunctions declared as virtual member functions inbase, then that override would be called at runtime.(On a somewhat related note,
derived::printhides the twobase::printmember functions, so if you were to try to use one of the base classprintfunctions, e.g.,derived().print(1, 1), it would fail. You would need to use a using declaration to make those member functions available during name lookup.)