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.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Apply for Computer Science Internship
- Apply for C++ Internship
- Practice Programming MCQs
- Practice Computer Science MCQs
- Check Programming Books