I have a strange situation over the following code. Please help me to get it clarified.
class B
{
public:
B();
virtual void print(int data=10)
{
cout << endl << "B--data=" << data;
}
};
class D:public B
{
public:
D();
void print(int data=20)
{
cout << endl << "D--data=" << data;
}
};
int main()
{
B *bp = new D();
bp->print();
return 0;
}
Regarding the output I expected
[ D--data=20 ]
But in practical it is
[ D--data=10 ]
Please help. It may seem obvious for you but I am not aware of the internal mechanism.
Default arguments are entirely compile-time feature. I.e. the substitution of default arguments in place of missing arguments is performed at compile time. For this reason, obviously, there’s no way default argument selection for member functions can depend on the dynamic (i.e. run-time) type of the object. It always depends on static (i.e. compile-time) type of the object.
The call you wrote in your code sample is immediately interpreted by the compiler as
bp->print(10)regardless of anything else.