inheritance, virtual methods, and overloaded methods

Hi,
I'm trying to compile this simple program

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
31
32
33
34
35
36
37
#include <iostream>
#include <string>

using namespace std;

class base{
public:
	virtual int foo(int  a)   { cout<<"base, foo, int\n"; return 2;}
        int foo(const string& s) { cout<<"base, foo, string\n"; return 2;}

	base(){}
	~base(){}
};

class derived: public base{
public:
	int  foo(int a)  {cout<<"derived, foo, int \n"; return 2;}

	derived(){}
	~derived(){}
};

int main()
{
	base B;
	derived D;

	B.foo(1);        //OK
	B.foo("aaa");    //OK

	D.foo(1);        //OK
	D.foo("aaa");    // not OK, why is that?
	

	cin.get();
	return 0;
}


my question is reflected in the code :) and what is the correct way to deal with this kind of constructions?
Names in derived class hides names in base class. In other words, your function "foo" in your derived class hides the foo function in your base class even though they take different types of parameters. This is the reason you get an error when you call D.foo("aaa"). You resolve this in two ways. You can either use a using declaration in your derived class like the one below.

1
2
3
4
5
6
7
8
class derived: public base{
public:
        using base::foo;
	int  foo(int a)  {cout<<"derived, foo, int \n"; return 2;}

	derived(){}
	~derived(){}
};


(or)
you could define another foo function in your derived class that takes a string parameter but implement by forwarding the call to the base class implementation of foo. You can call the base class version of foo using base::foo(string).

Scott Meyers's Effective C++ book discusses this issue in detail.
Ok, many thanks,

i did it myself in the second manner. Could be hard to guess about the first option.

and of course i'm getting this wonderful book )
Names in derived class hides names in base class. In other words, your function "foo" in your derived class hides the foo function in your base class even though they take different types of parameters.


Above contradict common sense and in this aspect, Java work what we expected.

Scott Meyers book is an essential read for anyone interested in those more in-depth C++ topics.
Topic archived. No new replies allowed.