Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale behind introducing protected access specifier

Tags:

c++

What was the rationale behind introducing protected access specifier in C++. An example would be helpful.

like image 476
ckv Avatar asked Jun 06 '10 04:06

ckv


2 Answers

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.

like image 67
fredoverflow Avatar answered Sep 22 '22 04:09

fredoverflow


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)

like image 21
SLaks Avatar answered Sep 25 '22 04:09

SLaks