Users Online

· Guests Online: 100

· 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 Illustrate Access Control in Inheritance

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

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.77 seconds
10,260,571 unique visits