Users Online
· Guests Online: 100
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
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.
-
/*
-
* C++ Program to illustrate access control in inheritance
-
*/
-
#include <iostream>
-
using namespace std;
-
-
class Base {
-
public:
-
int i;
-
void printValues() {
-
cout << "Base::i = " << i << "\n"
-
<< "Base::c = " << c << "\n"
-
<< "Base::d = " << d << "\n";
-
}
-
private:
-
char c;
-
protected:
-
double d;
-
Base() : i(0), c('a'), d(0) {}
-
-
};
-
-
class Derived : public Base {
-
public:
-
void changeI() {
-
i = 10;
-
cout << "Changing Base::i to 10\n";
-
}
-
void changeC() {
-
// c = 'j';
-
cout << "Unable to access Base::c\n";
-
}
-
void changeD() {
-
d = 10;
-
cout << "Changing Base::d to 10\n";
-
}
-
};
-
-
int main () {
-
Derived d;
-
-
d.printValues();
-
d.changeI();
-
d.changeC();
-
d.changeD();
-
d.printValues();
-
}
$ 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.