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.
/*
* C++ Program to Demonstrate use of Protected Members in Inheritance
*/
#include <iostream>
class Base {
private:
int i;
protected:
int j;
public:
int k;
Base(int ii = 0, int jj = 1, int kk = 2) : i(ii), j(jj), k(kk) { }
void printData() {
std::cout << "i (Private) = " << i << std::endl
<< "j (Protected) = " << j << std::endl
<< "k (Public) = " << k << std::endl;
}
};
class Derived : public Base {
public:
void changeData(void)
{
//Can access public and protected members in derived class
j++;
k++;
// But i++ show error
}
};
int main()
{
Derived d;
std::cout << "Before changing " << std::endl;
d.printData();
d.changeData();
std::cout << "After changing " << std::endl;
d.printData();
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Information Technology Internship
- Buy Computer Science Books
- Buy C++ Books
- Apply for Computer Science Internship
- Buy Programming Books