zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    falsh developer 快捷键
    FlashDevelop安装配置
    EditPlus保存时不生成bak文件(转)
    微信oauth2验证
    通过TortoiseSVN checkout的文件前面没有“状态标识”
    CSS3 Media Query 响应式媒体查询
    回车事件、键盘事件
    shiro登录密码加密
    mybatis常用类起别名
    shiro(四)项目开发中的配置、
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3444084.html
Copyright © 2011-2022 走看看