UPI Study › Courses › C++ Programming › Free lessons › Lesson 11.2 Free with a free account
Public, Private, and Protected
C++ Programming · Chapter 11: Inheritance and PolymorphismSection 11.2 · lesson 79 of 84video coming soon
← How Child Classes Inherit From ParentsNext lesson: Overriding Inherited Behavior →
In this lesson
Gatekeeping data access.
- Say who can reach public, protected and private members
- Combine member access with the inheritance mode
- Grant access deliberately with friend
- Explain why protected data draws suspicion
Transcript
Everything said in the video, section by section (1,208 words). Read along, or search it.
Overview
A Third Audience Arrives
Two access levels were enough while every type stood on its own. Inheritance introduces a third audience: types built on top of yours. With it comes a third specifier, a second place where access is decided, and a table that has to be read rather than guessed at. This section covers all of it, and ends with the advice experienced programmers give most often about it.
Core Idea
Who May Touch This Member
Access control answers one question. Who is allowed to touch this? Inheritance makes the answer three-valued. There's the type itself, and there's code outside it. And now there's a middle audience: types derived from it, which are neither the same type nor strangers. Private admits only the type itself. Protected also admits derived types. Public admits everyone, with no restriction.
Code Example
An Account With Three Specifiers
Here's an account with all three. Deposit is public, so anyone at all may call it. Record entry is protected, for this type and anything derived from it. And the balance is private, for this type only.
Access Table
Reading Access Row by Row
Read the table by row. Public is reachable from the type's own members, from a derived type, and from outside code. Protected is reachable from the first two, but not outside. Private is reachable only from the type's own members.
Outside Code
Strangers Refused at Compile Time
Outside code that tries gets refused. Calling deposit is fine. Calling record entry fails, and so does reading the balance. Here are the real errors.
Derived Type
What Savings Account Can Reach
Now a savings account derives from account. Inside add interest, calling deposit is allowed, because it's public in the base. Calling record entry is allowed too: it's protected, and this is a derived type. But touching balance is refused, because it's private to account. Run it and both allowed calls work.
Key Error
Balance Is Present but Unnameable
That refused line is the important one. Remove the comment marks, and the compiler stops you. Here is the real error. Balance is present in every savings account object, taking up space, and no code in savings account may mention it. If the derived type genuinely needs to change the balance, the base must offer a way, under its own rules. Inheritance isn't membership. It's closer to being handed the outside of the base, plus one extra door.
Second Decision
The Inheritance Mode
Access is decided twice. The first decision is the specifier on each member. The second is the mode, written at the point of derivation: public, protected or private. Private is also the default, if the word is left out.
Mode Table
How Each Mode Changes Access
Read the table down for a member's marking in the base, and across for the mode. Under public inheritance, nothing changes. Under protected, public members are pulled down to protected. Under private, everything inherited becomes private. And a private base member is not accessible, in every mode.
Mental Model
The Mode as a Ceiling
Think of the mode as a ceiling. A member's access in the derived type is whichever is more restrictive: its own marking, or the mode. Two consequences are worth stating in words. A private base member is out of reach in the derived type, whatever mode is chosen. So no mode is a way around privacy. And the mode can tighten access on the way down, but never loosen it.
Who Feels It
Modes Describe What Is Exposed
The mode's effect is felt not inside the derived type, but by everybody using it. A savings account inherits publicly, so calling deposit on one is allowed. It's still public. A ledger inherits privately, so calling deposit on a ledger from outside is refused. Deposit became private in ledger. But inside ledger's own members, deposit is perfectly usable. So the modes are statements about what the derived type exposes, not about what it can use.
Reach Summary
Reaching a Public Base Member
Reaching a public base member works like this. From inside the derived type, it's reachable under all three modes. From a further derived type, it works under public and protected inheritance, but not private. And from ordinary code holding an object, only public inheritance allows it.
Friend
Granting Access by Name
Occasionally a function or another type genuinely needs to reach inside. An auditing routine, say, or a companion type working on the same data. A friend declaration grants that access, by name. Here, account names one function, audit, as a friend, and one whole type, regulator. So audit may read the private balance directly. Run it: both print the balance.
Friend Rules
Four Properties of Friendship
Friendship has four properties that are easy to assume wrongly. It's granted, never taken. Only the type can name a friend, so access control is never bypassed against its wishes. It's not reciprocal. Account naming regulator a friend doesn't open regulator to account. It's not inherited. A friend of a base isn't a friend of derived types, and a type derived from a friend doesn't inherit the friendship. And it's not transitive. A friend of my friend is a stranger to me. Because the declaration is written inside the type, anyone reading it sees the full list. It's an exception with a name, not a hole.
Quick Check
Calling Deposit From Report
Quick check. Ledger inherits privately from account, and report inherits publicly from ledger. Can report's own member function call deposit? Pause and think.
Answer
Private in Ledger Blocks Report
No. Deposit became private in ledger, so report, which derives from ledger, can't reach it. Here is the real error.
Design Warning
The Trouble With Protected Data
Marking data protected feels like the obvious middle ground. It's also the one choice here that experienced programmers routinely warn against. On the left, the data is protected. A derived type can set it to anything, including states the base considers impossible. On the right, the data is private, and a protected function does the acting.
Reasoning
Wide Promise Versus Narrow Contract
With protected data, every derived type ever written depends on the exact representation, including ones you've never seen. With a protected function, nobody does. You can't change how protected data is stored without breaking derived types. Behind a function, you can rewrite freely. A derived type can set protected data to anything. A function can check, adjust, or refuse. So the promise of protected data is as wide as inheritance goes. A function's promise is as narrow as its contract.
Practical Rule
Private Data, Protected Functions
The practical rule is short. Keep data private. Where derived types need to act on it, provide a protected function that does the acting. The derived type gets what it actually needed, the ability to perform an operation, and the base keeps control of storage and valid states. Protected data isn't forbidden, and is sometimes right. It's simply a promise made to every future derived type, and promises made to people you haven't met are hard to withdraw.
Vocabulary
Key Terms Defined
Protected means reachable by the type itself and its derived types, but not by outside code. The inheritance mode is the specifier at the point of derivation, setting a ceiling on inherited access. Under private inheritance, every inherited member becomes private. It's the default when the word is omitted. A friend is a function or type a type names as permitted to reach its private members. Representation is how a type stores its values. And an invariant is a rule about an object's state, which its own members maintain.
Key Takeaways
Access Rules in Summary
To summarize. Public admits everyone, protected admits the type and derived types, and private admits only the type. Derived objects contain private base members, but can't name them. The inheritance mode only ever restricts, and never reaches private members. Friend grants access by name. It's never taken, and never reciprocal, inherited, or transitive. And keep data private, giving derived types protected functions.
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Public, Private, and Protected
What is the difference between public, protected, and private members in C++?
Can a derived class access private members of its base class in C++?
How does public, protected, or private inheritance change member access in C++?
Why do experienced C++ programmers avoid protected data members?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →