VOOZH about

URL: https://www.geeksforgeeks.org/cpp/what-happens-when-more-restrictive-access-is-given-in-a-derived-class-method-in-c/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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. 

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

What about the below program? 

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. 
 

Comment
Article Tags:
Article Tags: