How to use of Protected Data Member in C++ with example


A protected member can be accessed by member functions in its own class or in any class derived from its own class. It can't be accessed from functions outside these classes, such as main(). This is just what we want. Hence the protected access specifier is used.

You would agree that through the derived class both we have increased the functionality of the increment class without modifying it. This is the power of inheritance.

Simple Example of Protected Data Member in C++

#include<iostream> using namespace std; class increment{ protected: int count; public: increment(){ count = 0; } void operator++(int){ count++; } void print(){ cout<<count<<endl; } }; class both : public increment{ public: void operator --(int){ count --; } }; int main(){ both b; b.print(); b++; b++; b++; b++; b.print(); b--; b.print(); return 0; }

Output:-

0
4
3

Explanation of the program

We don't want to make count public since that would allow it to be accessed through any function anywhere in the program and thereby eliminate the advantage of data hiding.