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.

This article is written by our awesome writer
Comments to: How to use of Protected Data Member in C++ with example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password