Users Online

· Guests Online: 44

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

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

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.74 seconds
10,820,551 unique visits