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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Difference between Base class and Derived class in C++
- Can we access private data members of a class without using a member or a friend function?
- Derived Data Types in C++
- Virtual functions in derived classes
- Catching base and derived classes as exceptions
- Publicly inherit a base class but making some of public method as private
- Difference between fundamental data types and derived data types
- Access Modifiers in C++
- How to convert a class to another class type in C++?
- Random-access Iterators in C++
- How to bind to port number less than 1024 with non root access?
- Can we access global variable if there is a local variable with same name?
- std::any Class in C++
- Array class in C++
- std::string class in C++
- std::hash class in C++ STL
- std:: valarray class in C++
- Structure vs class in C++
- Simulating final class in C++
- std::bad_weak_ptr class in C++ with Examples