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

  • 相关阅读:
    Objective-C 和 Core Foundation 对象相互转换
    sql学习笔记(18)-----------数据库创建过程
    JVM虚拟机结构
    自己定义控件-MultipleTextView(自己主动换行、自己主动补齐宽度的排列多个TextView)
    Blue Jeans
    怎样注冊 diskgroup 到集群
    改动购物项图书数量的Ajax处理
    leetcode_Integer to Roman
    Buildroot 龙芯1C支持指南
    Buildroot構建指南--Overview【转】
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3444084.html
Copyright © 2011-2022 走看看