C++ Program to Demonstrate use of Protected Members in Inheritance

This C++ program demonstrates the use of protected members in inheritance. The Base Class has all types of members namely – Public, Private and Protected. The public members are accessible from anywhere, the private members are accessible only within class and the protected members are accessible from the base class or its derived class.

Here is the source code of the C++ program demonstrates the use of protected members 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 Demonstrate use of Protected Members in Inheritance
  3.  */
  4. #include <iostream>
  5.  
  6. class Base {
  7.     private:
  8.         int i;
  9.     protected:
  10.         int j;
  11.     public:
  12.         int k;
  13.         Base(int ii = 0, int jj = 1, int kk = 2) : i(ii), j(jj), k(kk) { }
  14.         void printData() {
  15.             std::cout << "i (Private) = " << i << std::endl
  16.                       << "j (Protected) = " << j << std::endl
  17.                       << "k (Public) = " << k << std::endl;
  18.         }
  19. };
  20.  
  21. class Derived : public Base {
  22.     public:
  23.         void changeData(void)
  24.         {
  25.             //Can access public and protected members in derived class
  26.             j++;
  27.             k++;
  28.             // But i++ show error
  29.         }
  30. };
  31.  
  32. int main()
  33. {
  34.     Derived d;
  35.  
  36.     std::cout << "Before changing " << std::endl;
  37.     d.printData();
  38.     d.changeData();
  39.     std::cout << "After changing " << std::endl;
  40.     d.printData();
  41. }

$ a.out
Before changing 
i (Private) = 0
j (Protected) = 1
k (Public) = 2
After changing 
i (Private) = 0
j (Protected) = 2
k (Public) = 3

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.