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