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


In this section we will discuss about interesting facts restrictive access of derived class methods in C++. We will see some examples and analyze the output to know more about restrictions of using derived class methods in C++.

Example (C++)

Let us see the following implementation to get better understanding −

#include <iostream>
using namespace std;
class BaseClass {
public:
   virtual void display(){
      cout << "Print function from the base class" << endl;
   }
};
class DerivedClass: public BaseClass {
private:
   void display() {
      cout << "Print function from the derived class" << endl;
   }
};
int main() {
}

This is fine, now if we replace the main function block with this, we will get an error like below −

int main() {
   DerivedClass d;
   d.display();
}

Output

main.cpp: In function ‘int main()’:
main.cpp:20:15: error: ‘virtual void DerivedClass::display()’ is private
within this context
d.display();
^
main.cpp:13:10: note: declared private here
void display() {
^~~~~~~

It shows an error as the method in derived class is private. Now let see this implementation, where the function is called using the base pointer. This can call the function.

Example (C++)

 Live Demo

#include <iostream>
using namespace std;
class BaseClass {
public:
   virtual void display(){
      cout << "Print function from the base class" << endl;
   }
};
class DerivedClass: public BaseClass {
private:
   void display() {
      cout << "Print function from the derived class" << endl;
   }
};
int main() {
   BaseClass *b = new DerivedClass;
   b->display();
}

Output

Print function from the derived class

From the above program, we can see that the private function DerivedClass::display() is being called through the base class pointer, the program works fine as display() function is public in base class. The access specifiers are verified at compile time and display() is public in base class. During run time, only the function corresponding to the pointed object is called and access specifier is not verified. So a private function of derived class is being called through a pointer of base class.

Updated on: 27-Aug-2020

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements