Interview Question
Country: India
shondik, can you elaborate on that? Since I am not sure I understand the slightly modified version below.
class base{
public:
virtual void func(int i,int j=10)
{
cout<<"base func"<<endl;
}
};
class der:public base
{
public:
void func(int i,int j=5)
{
cout<<"der "<<j<<" func"<<endl;
}
};
int main()
{
der dd;
base *bb = new der();
bb->func(10);
dd.func(10,1);
dd.func(10,5);
}
Output is:
- Aashish July 14, 2012der 10 func
der 1 func
The explanation goes as follows:
The default argument is a compile-time feature i.e. the substitution of default arguments is done at compile-time.
For this reason, obviously, there's no way the default argument mechanism 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[bb->func(10)] is immediately interpreted by the compiler as bb->func(10,10) regardless of anything else.