C++ Program to Demonstrate the use of Access Control Specifiers
Posted by Superadmin on August 10 2022 08:18:01

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