Public, Private, and Protected, Explained with Code Examples

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 →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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++?
Public members are reachable by everyone, protected members by the class itself and its derived classes, and private members only by the class itself. Outside code can call a public function such as deposit but gets a compile error for a protected function or a private balance. Derived classes sit in the middle, between the class itself and outsiders.
Can a derived class access private members of its base class in C++?
No, a derived class cannot name a private base member, no matter which inheritance mode is used. The private data still exists inside every derived object and takes up space, but code in the derived class that mentions it will not compile. If the derived class must change it, the base class has to provide a public or protected function.
How does public, protected, or private inheritance change member access in C++?
The inheritance mode acts as a ceiling, so a member's access in the derived class is the more restrictive of its own marking and the mode. Public inheritance changes nothing. Protected inheritance makes public members protected. Private inheritance makes all inherited members private. A private base member stays inaccessible in every mode, so the mode can tighten access but never loosen it.
Why do experienced C++ programmers avoid protected data members?
Protected data lets every derived class depend on the exact storage and set values the base considers invalid. You then cannot change the representation without breaking derived classes, including ones you have never seen. The usual advice is to keep data private and offer a protected function that performs the operation. The base can then check values and keep control of its invariants.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

C++ Programming
3 credits · NCCRS
Enroll →