What was the rationale behind introducing protected access specifier in C++. An example would be helpful.
What was the rationale behind introducing protected access specifier in C++. An example would
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
protectedaccess level is used when classes need to work together with their inheritors.For example, imagine an abstract
Shapeclass 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
Shapeclass might have a publicgetArea()method that returns a private variable holding the area.The best way to set this variable would be a
protectedmethod calledsetArea(double)which would be called by the child classes.Thus,
Circlewould callsetArea(PI * radius * radius),Squarewould callsetArea(side * side), etc.Note that this is not necessarily a good design (but it’s a great example of
protected)