P28-c++ class inheritance-05 access control: protected

Article Directory

1. Access control: protected

So far, the class examples in this book have used the keywords public and private to control access to class members. There is another access category, which is represented by the keyword protected.
The keyword protected is similar to private. Only public class members can be used outside the class to access the class members in the protected section.
The difference between private and protected is only manifested in classes derived from the base class.

The members of the derived class can directly access the protected members of the base class, but cannot directly access the private members of the base class. Therefore, for the outside world, the behavior of protecting members is similar to that of private members: but for derived classes, the behavior of protecting members is similar to that of public members.

For example, if the Brass class declares the balance member as protected

Class Brass
{
    
    
protected:
	double balance;
};

In this case, the BrassPlus class can directly access the balance without using the Brass method.

Using protected data members can simplify code writing, but there are design flaws. For example, continuing to take BrassPlus as an example, if the balance is protected, you can write the code as follows:

void BrassPlus::Reset(double amt)
{
    
    
	balance = amt;
}

The Brass class is designed to modify the balance only through Deposit() and Withdraw(). But for the BrassPlus object, the Reset() method will ignore the protection measures in Withdraw() and actually make the balance a public variable.

Warning: It is best to use private access control for class data members, do not use protected access control; at the same time, the derived class can access the base class data through the base class method.

However, for member functions, it is useful to protect access control, which allows derived classes to access internal functions that are not available to the public.

Guess you like

Origin blog.csdn.net/sgy1993/article/details/113872847