Function overriding and default parameters

Hi all,
I read one example, according to which the following code is supposed to override base::fx with child::fx, but it doesn't:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

struct base
{
 virtual void fx() {cout << "base fx!" << endl;}
};

struct child:
public base
{
 virtual void fx(int i = 1) {cout << "child fx with i == " << i << "." << endl;}
};

int
main(int, char**)
{
 child c;
 c.base::fx();
 c.fx();
 c.fx(2);

 cout << endl;

 base& br = c;
 br.base::fx();
 br.fx(); // ?! not child?! WHY?

 return 0;
}

So why was such an example created, any idea? Are there any cases where there would be an overriding by using the default value as in child::fx?
fx(int) and fx() are two different functions, therefore child::fx is not reimplementing base::fx. Default parameters are simply a conveinience thing, and can't be used to change the behavior of the underlying function.

If you want to mimic that behavior you can do the following:

1
2
3
4
5
6
struct child:
public base
{
 virtual void fx() { fx(1); /* call the other function instead of a default param*/ }
 virtual void fx(int i) {cout << "child fx with i == " << i << "." << endl;}
};

Topic archived. No new replies allowed.