C++ Protected: Usage Guide for Developers

In C++, the protected keyword is used to declare a class’s member attributes and methods that can be accessed by the class’s derived classes but not directly by objects of the class.

When using the keyword protected, members declared as protected can be accessed within the class and its derived classes. An example is shown below:

class Base {
protected:
    int protectedVar;

public:
    Base() {
        protectedVar = 10;
    }

    void printProtectedVar() {
        cout << "Protected Variable: " << protectedVar << endl;
    }
};

class Derived : public Base {
public:
    void modifyProtectedVar() {
        protectedVar = 20;
        cout << "Modified Protected Variable: " << protectedVar << endl;
    }
};

int main() {
    Base obj;
    obj.printProtectedVar(); // 在类的成员函数中访问protected成员

    Derived derivedObj;
    derivedObj.modifyProtectedVar(); // 在派生类的成员函数中访问protected成员

    return 0;
}

In this example, the Base class declares a protected member variable protectedVar and defines a member function printProtectedVar to access this member variable. The Derived class inherits from the Base class, and defines a member function modifyProtectedVar to modify the value of protectedVar. In the main function, objects are created for both the Base class, obj, and the Derived class, derivedObj, and their respective member functions are called to access and modify the protected member.

bannerAds