What happens when more restrictive access is given to a derived class method in C++?

 

  We have discussed a similar topic in Java here. Unlike Java, C++ allows to give more restrictive access to derived class methods.

  For example the following program compiles fine.

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Base 
 5 {
 6 public:
 7     virtual int fun(int i) 
 8     { 
 9     }
10 };
11 
12 class Derived: public Base 
13 {
14 private:
15     int fun(int x)   
16     {  
17     }
18 };
19 
20 int main()
21 {  
22 }

 

  In the above program, if we change main() to following, will get compiler error becuase fun() is private in derived class.

1 int main()
2 {
3     Derived d;
4     d.fun(1);
5     return 0;
6 }


  What about the below program?

 1 #include<iostream>
 2 using namespace std;
 3  
 4 class Base 
 5 {
 6 public:
 7     virtual void fun(int i) 
 8     { 
 9         cout << "Base::fun(int i) called"; 
10     }
11 };
12  
13 class Derived: public Base 
14 {
15 private:
16     void fun(int x)   
17     { 
18         cout << "Derived::fun(int x) called"; 
19     }
20 };
21  
22 int main()
23 {
24     Base *ptr = new Derived;
25     ptr->fun(10);
26     return 0;
27 }

  Output:

   Derived::fun(int x) called
  

  In the above program, private function “Derived::fun(int )” is being called through a base class pointer, the program works fine because fun() is public in base class. Access specifiers are checked at compile time and fun() is public in base class. At run time, only the function corresponding to the pointed object is called and access specifier is not checked. So a private function of derived class is being called through a pointer of base class.

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  20:42:53

posted @ 2013-11-26 20:44  虔诚的学习者  阅读(146)  评论(0编辑  收藏  举报