Protected
In C++, the protected
access specifier is used to define the accessibility of class members. Members declared as protected
are accessible within the class itself and by its derived classes (subclasses).
This approach balances encapsulation and inheritance by restricting access while enabling derived classes to extend functionality.
Syntax
The following syntax defines a base class with two protected
members that can be accessed from derived classes:
class BaseClass {
protected:
// Protected members
int myVar;
void myFunc();
};
Example
The following example demonstrates the use of the protected
access specifier in C++:
#include <iostream>using namespace std;// Base classclass BaseClass {protected:int myVar;void myFunc() {cout << "Accessing protected function from BaseClass" << endl;}};// Derived classclass DerivedClass : public BaseClass {public:void useProtectedMembers() {myVar = 10; // Accessing protected variablecout << "Protected variable value: " << myVar << endl;myFunc(); // Accessing protected function}};int main() {DerivedClass obj;obj.useProtectedMembers();// The following lines will cause compilation errors if uncommented// obj.myVar = 20;// obj.myFunc();return 0;}
In this example:
BaseClass
includes a protected variable myVar
and a protected function myFunc()
, which DerivedClass
can access and modify through inheritance.
In the main
function, useProtectedMembers()
demonstrates accessing these members in a controlled manner.
Note: Attempts to access protected members directly from objects of
BaseClass
orDerivedClass
result in compilation errors, maintaining encapsulation.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours