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.
Like any other function, a virtual function can have default arguments (§ 6.5. 1, p. 236). If a call uses a default argument, the value that is used is the one defined by the static type through which the function is called.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
Yes, C++ virtual functions can have default parameters.
The standard says (8.3.6.10):
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.
This means, since you are calling print
through a pointer of type B
, it uses the default argument of B::print
.
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