Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function default arguments behaviour

Tags:

c++

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 image 550
paper.plane Avatar asked Jun 24 '11 06:06

paper.plane


People also ask

Can virtual functions have default arguments?

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.

What are default arguments in functions?

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.

Can virtual functions have parameters?

Yes, C++ virtual functions can have default parameters.


1 Answers

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.

like image 154
Björn Pollex Avatar answered Sep 23 '22 09:09

Björn Pollex