Ray's playground

 

Item 33: Avoid hiding inherited names(Effective C++)

Names in derived classes hide names in base classes. Under public inheritance, this is never desirable.

To make hidden names visible again, employ using declarations or forwarding functions.

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base
 5 {
 6     private:
 7         int x;
 8 
 9     public:
10         virtual void mf1() = 0;
11         virtual void mf1(int)
12         {
13             cout << "mf1(int) in base" << endl;
14         }
15 
16         virtual void mf2()
17         {
18             cout << "mf2 in base" << endl;
19         }
20 
21         void mf3()
22         {
23             cout << "mf3 in base" << endl;
24         }
25 
26         void mf3(double)
27         {
28             cout << "mf3(double) in base" << endl;
29         }
30 };
31 
32 class Derived: public Base 
33 {
34     public:
35         using Base::mf1;       // make all things in Base named mf1 and mf3
36         using Base::mf3;       // visible (and public) in Derived's scope
37 
38         virtual void mf1()
39         {
40             cout << "mf1 in derived" << endl;
41         }
42         
43         void mf3()
44         {
45             cout << "mf3 in derived" << endl;
46         }
47         
48         void mf4()
49         {
50             cout << "mf4 in derived" << endl;
51         }
52 };
53 
54 
55 
56 int main()
57 {
58     Derived d;
59 
60     int x = 0;
61     d.mf1();                 // still fine, still calls Derived::mf1
62 
63     d.mf1(x);                // now okay, calls Base::mf1
64 
65     d.mf2();                 // still fine, still calls Base::mf2
66 
67     d.mf3();                 // fine, calls Derived::mf3
68 
69     d.mf3(x);                // now okay, calls Base::mf3
70 
71     cin.get();
72 
73     return 0;
74 }

posted on 2011-04-02 09:50  Ray Z  阅读(195)  评论(0编辑  收藏  举报

导航