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
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]Related Posts:
- Apply for C++ Internship
- Practice Computer Science MCQs
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Programming Books