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

  • 相关阅读:
    table固定头部,tbody内容滚动
    js 中json遍历 添加 修改 类型转换
    SEO优化
    JS对字符串的操作,截取
    移动端 去掉滚动栏
    JS 引擎的执行机制
    Uncaught SyntaxError: Unexpected token ILLEGAL
    利用css 画各种三角形
    js文本公告滚动展示,图片轮播....
    js判断手指的上滑,下滑,左滑,右滑,事件监听
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3444084.html
Copyright © 2011-2022 走看看