C++ Program to Illustrate Access Control in Inheritance

This C++ program illustrates access control in inheritance. The access control can be managed with three keywords – public, private and protected. The public keyword allows access by every class, the private doesn’t allow access by any class and the protected keyword works just like private except for the classes inherited from the base class, where the elements declared protected are visible in the classes derived from it.

Here is the source code of the C++ program which illustrates access control in inheritance. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate access control in inheritance
  3.  */
  4. #include <iostream>        
  5. using namespace std;
  6.  
  7. class Base {
  8.     public:
  9.         int i;
  10.         void printValues() {
  11. 	    cout << "Base::i = " << i << "\n"
  12. 	    	 << "Base::c = " << c << "\n"
  13. 	    	 << "Base::d = " << d << "\n";
  14. 	}
  15.     private:
  16.         char c;
  17.     protected:
  18.         double d;
  19.     Base() : i(0), c('a'), d(0) {}
  20.  
  21. };
  22.  
  23. class Derived : public Base {
  24.     public:
  25.         void changeI() {
  26. 	    i = 10;
  27. 	    cout << "Changing Base::i to 10\n";
  28. 	}
  29. 	void changeC() {
  30. 	    // c = 'j';
  31. 	    cout << "Unable to access Base::c\n";
  32. 	}
  33. 	void changeD() {
  34. 	    d = 10;
  35. 	    cout << "Changing Base::d to 10\n";
  36. 	}    
  37. };
  38.  
  39. int main () {
  40.     Derived d;
  41.  
  42.     d.printValues();
  43.     d.changeI();
  44.     d.changeC();
  45.     d.changeD();
  46.     d.printValues();
  47. }

$ gcc test.cpp
$ a.out
Base::i = 0
Base::c = a
Base::d = 0
Changing Base::i to 10
Unable to access Base::c
Changing Base::d to 10
Base::i = 10
Base::c = a
Base::d = 10

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.