I'm working on C++. Following is my code:
#include <iostream>
using namespace std;
class base
{
public:
virtual void display(int a = 4)
{
cout << "base :: "<< a*a << endl;
}
};
class derived : public base
{
public:
void display(int b = 5)
{
cout << " Derived :: " << b*b*b << endl;
}
};
int main()
{
base *bobj;
derived dobj;
bobj = &dobj;
bobj->display();
return 0;
}
The output is:
Derived :: 64
The function of Base class is called, but default value of the parameter of derived function is used. Why the derived class method display(), takes the base class method argument value?
Because you're calling it through a pointer to base
. That's how it works.
Arguments are pushed on the argument stack (or inside registers) before the actual call. Because you have a pointer to base
and no parameters, the default 4
is passed to the function. Then the correct function is called (derived::display
), but with base
's default parameter. Of course, this is an implementation detail, but the behavior is standard.
A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
I would provide emphasis on the quote, but the whole thing is pretty self-explanatory.
dobj.display();
would print 125
(5^3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With