C++ Program to Demonstrate the use of Access Control Specifiers

This C++ program illustrates the use of access control specifiers in a class. The three access control specifiers are as follows : public – member is visible to the user and derived classes, private – member is not visible to the user and derived classes and protected – member is visible to the derived class but not to the user.

Here is the source code of the C++ program illustrates the use of access control specifiers in a class. 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 the use of Access Control Specifiers
  3.  */
  4. #include <iostream>
  5.  
  6. class Base {
  7.     private:
  8.         int a;
  9.     protected:
  10.         int b;
  11.     public:
  12.         int c;
  13.         Base(int aa = 1, int bb = 2, int cc = 3) : a(aa), b(bb), c(cc) {}
  14.         virtual ~Base() {}
  15. };
  16.  
  17. class Derived: public Base {
  18.     int j;
  19.     public:
  20.         Derived(int jj = 0) : j(jj) {}
  21.         void change()
  22.         {
  23.            // 'b' is protected
  24.            j = b;
  25.         }
  26.         void printValue()
  27.         {
  28.             std::cout << "Derived::j = " << j
  29.                       << std::endl;
  30.         }
  31. };
  32.  
  33. int main()
  34. {
  35.     Base base;
  36.     Derived derived;
  37.  
  38.     // 'a' and 'b' are private and protected
  39.     // std::cout << base.a << std::endl;
  40.     // std::cout << base.b << std::endl;
  41.     std::cout << "Base::c = "<< base.c << std::endl;
  42.     derived.change();
  43.     derived.printValue();
  44. }

$ a.out
Base::c = 3
Derived::j = 2

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.