Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 18 May, 2021

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. 

C++




#include<iostream>
using namespace std;
 
class Base {
public:
    virtual int fun(int i) { }
};
 
class Derived: public Base {
private:
    int fun(int x)   {  }
};
 
int main()
{  }

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

C++




int main()
{
    Derived d;
    d.fun(1);
    return 0;
}

What about the below program? 

C++




#include<iostream>
using namespace std;
 
class Base {
public:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
 
class Derived: public Base {
private:
    int fun(int x)   { cout << "Derived::fun(int x) called"; }
};
 
int main()
{
    Base *ptr = new Derived;
    ptr->fun(10);
    return 0;
}

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
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :