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 becuase fun() is private in derived class.
What about the below program?
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference between Base class and Derived class in C++
- Virtual functions in derived classes
- Catching base and derived classes as exceptions
- Difference between fundamental data types and derived data types
- Derived Data Types in C++
- What happens when a function is called before its declaration in C?
- What happens if loop till Maximum of Signed and Unsigned in C/C++?
- What happens when a virtual function is called inside a non-virtual function in C++
- what happens when you don't free memory after using malloc()
- What happens if we mix new and free in C++?
- How to access private/protected method outside a class in C++
- Can we access private data members of a class without using a member or a friend function?
- Write a C program that displays contents of a given file like 'more' utility in Linux
- How to convert a class to another class type in C++?
- Can we access global variable if there is a local variable with same name?
- How to bind to port number less than 1024 with non root access?
- Random-access Iterators in C++
- Access Modifiers in C++
- Publicly inherit a base class but making some of public method as private
- What all is inherited from parent class in C++?