What was the rationale behind introducing protected access specifier in C++. An example would be helpful.
For these kind of questions, I recommend The Design And Evolution of C++ by Bjarne Stroustrup. Section 13.9 describes the evolution of protected members.
Shortly after Release 1.0 [of Cfront], Mark Linton stopped by my office and made an impassioned plea for a third level of access control [...] He argued persuasively based on genuine experience and examples from real code that protected data was essential for the design of an efficient and extensible X windows toolkit. [...] These were good arguments and essentially the ones that convinced me to allow protected members. [...]
Five years or so later, Mark banned the use of protected data members in Interviews [the X windows toolkit mentioned earlier] because they had become a source of bugs. [...] They also seriously complicate maintenance [...]
Protected members were introduced into Release 1.2. Protected base classes were first described in Release 2.1. In retrospect, I think that
protected
is a case where "good arguments" and fashion overcame my better judgement and my rules of thumb for accepting new features.
The protected
access level is used when classes need to work together with their inheritors.
For example, imagine an abstract Shape
class that can report its area to the outside world.
Different shapes, such as triangles, squares, and circles, are described differently (angle, side, radius) and calculate their areas differently.
The Shape
class might have a public getArea()
method that returns a private variable holding the area.
The best way to set this variable would be a protected
method called setArea(double)
which would be called by the child classes.
Thus, Circle
would call setArea(PI * radius * radius)
, Square
would call setArea(side * side)
, etc.
Note that this is not necessarily a good design (but it's a great example of protected
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With