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
38
39
40
41
42
43
44
45
46
47
| #include <string> class Person { private : std::string m_strName; int m_nAge; bool m_bIsMale; public : Person(std::string strName, int nAge, bool bIsMale) : m_strName(strName), m_nAge(nAge), m_bIsMale(bIsMale) { } std::string GetName() { return m_strName; } int GetAge() { return m_nAge; } bool IsMale() { return m_bIsMale; } }; class Employee { private : std::string m_strEmployer; double m_dWage; public : Employee(std::string strEmployer, double dWage) : m_strEmployer(strEmployer), m_dWage(dWage) { } std::string GetEmployer() { return m_strEmployer; } double GetWage() { return m_dWage; } }; // Teacher publicly inherits Person and Employee class Teacher: public Person, public Employee { private : int m_nTeachesGrade; public : Teacher(std::string strName, int nAge, bool bIsMale, std::string strEmployer, double dWage, int nTeachesGrade) : Person(strName, nAge, bIsMale), Employee(strEmployer, dWage), m_nTeachesGrade(nTeachesGrade) { } }; |
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
38
39
40
41
42
43
44
| class USBDevice { private : long m_lID; public : USBDevice( long lID) : m_lID(lID) { } long GetID() { return m_lID; } }; class NetworkDevice { private : long m_lID; public : NetworkDevice( long lID) : m_lID(lID) { } long GetID() { return m_lID; } }; class WirelessAdaptor: public USBDevice, public NetworkDevice { public : WirelessAdaptor( long lUSBID, long lNetworkID) : USBDevice(lUSBID), NetworkDevice(lNetworkID) { } }; int main() { WirelessAdaptor c54G(5442, 181742); cout << c54G.GetID(); // Which GetID() do we call? return 0; } |
c54G.GetID()
is evaluated, the compiler looks to see if WirelessAdaptor contains a function named GetID(). It doesn’t. The compiler then looks to see if any of the base classes have a function named GetID(). See the problem here? The problem is that c54G actually contains TWO GetID() functions: one inherited from USBDevice, and one inherited from WirelessDevice. Consequently, this function call is ambiguous, and you will receive a compiler error if you try to compile it.
1
2
3
4
5
6
7
| int main() { WirelessAdaptor c54G(5442, 181742); cout << c54G.USBDevice::GetID(); return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class PoweredDevice { }; class Scanner: public PoweredDevice { }; class Printer: public PoweredDevice { }; class Copier: public Scanner, public Printer { }; |
0 comments: