How Child Classes Inherit From Parents | C++ Programming

UPI Study › Courses › C++ Programming › Free lessons › Lesson 11.1 Free with a free account

How Child Classes Inherit From Parents

C++ Programming · Chapter 11: Inheritance and PolymorphismSection 11.1 · lesson 78 of 84video coming soon

← Memory Lifecycle DrillsNext lesson: Public, Private, and Protected →

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

In this lesson

Extending existing blueprints.

  • Write an inheritance declaration; say what is inherited
  • Apply the is-a test, and choose composition when it fits
  • Predict construction and destruction order
  • Pass base arguments; recognize the 4 hierarchy shapes

Transcript

Everything said in the video, section by section (1,406 words). Read along, or search it.

Opening Question

Why Types Build on Each Other

Types in a real system are rarely unrelated. A manager is an employee with extra responsibilities. A savings account is an account with an interest rule. Inheritance lets you say that directly. You describe what's shared once, and only the differences in each type that builds on it. It's also the most overused feature in object-oriented design, so knowing when not to reach for it matters as much as knowing how.

Definition

Base and Derived Class Syntax

The class being built on is the base, also called the parent. The class building on it is the derived class, or child. Here, employee has a name, an id and pay, with functions that report them. The declaration of manager names its base after a colon: class manager, colon, public employee. Manager adds only a team size, and the one function that reports it. The word public controls how inherited members appear to outside code. It's the usual choice, and the alternatives come in the next section.

Worked Example

A Manager Contains an Employee

A manager now has everything an employee has: the name, the id, the pay, and the functions that report them. Plus whatever it adds. Inside, a manager object contains a complete employee object, intact, with manager's additions alongside it. So you can call base pay on a manager, inherited from employee, and team size, which is manager's own. Run it. Nothing was copied and nothing was repeated. The shared part is described once, in one place, and corrected in one place.

Key Rule

What Derived Classes Do Not Inherit

Data members are inherited, because every derived object contains a complete base object. Member functions are inherited too, callable as though they'd been written in the derived class. But constructors, the destructor, and assignment are not. One idea covers all three. Anything concerned with creating, copying, or destroying an object belongs to the exact type being created. The derived class always supplies its own. But it never reimplements the base's part of the job, because the base's version is invoked for it.

Design Test

Inheritance Must Mean Is-A

Inheritance isn't a mechanism for sharing code. It's a statement about meaning. It says every derived object is a base object, and may be used anywhere one is expected. So say the sentence out loud, and check it's true without qualification. A manager is an employee. A savings account is an account. Both pass. A car isn't a kind of engine. It has one, and four wheels, which inheritance couldn't express at all. A stack built on a vector would hand callers indexing and insertion in the middle, breaking the rule that makes it a stack. And a square is mathematically a rectangle, but setting width and height independently is nonsense for a square. The real test is whether a derived object can be used everywhere a base one can, without surprising anybody.

Alternative

Has-A Means Member Variable

When the answer is has-a, the tool is a member variable. On the left, manager is an employee, and offers everything one does. On the right, a car has an engine, four wheels and a battery, as members. And it exposes only what it chooses. It's the same arrangement you've used since structs first held other structs.

Comparison

Choosing Inheritance or Composition

So how do you choose? Inheritance says is a kind of. Composition says has one, or is built from. With inheritance, the base's whole public interface comes along, suitable or not. With composition, you expose exactly what you choose. Inheritance gives one base part of each kind. Composition allows as many members as you like. Changing inheritance later is awkward, because callers may depend on it. Changing a member affects only this class. Inheritance is a permanent, public commitment. Composition promises nothing outside. When both would work, the one that promises less is easier to change, and that's usually the deciding argument. So the default choice is composition, and inheritance only when is-a is plainly true.

Quick Check

Predict the Six Printed Lines

Quick check. Here, C derives from B, which derives from A, and each constructor and destructor prints a line. Making one C object: in what order do the six lines print? Pause and predict.

Answer Explained

Build Down the Chain, Destroy Up

Creating a derived object means creating the base part first. That isn't a convention. It's a necessity, since the derived class's setup may use what the base provides, and it can't use what doesn't exist yet. Run it. Making one C object prints A, B, C on construction. And destruction runs in the exact reverse: C, B, then A. Picture the chain from the most general type at the top, down to the type you asked for. Construction goes down the chain. Destruction comes back up. So the base part is ready before the derived setup runs, and torn down only after the derived cleanup finishes.

Syntax

Passing Arguments to the Base

The base needs its own arguments, and there's exactly one place to supply them. It's the derived constructor's initializer list, between the parameter list and the body. Here, manager's constructor passes the name and id to employee's constructor, then sets its own reports member. It has to go there, because by the time the body starts, the base part is already built. Run it: the employee line prints first, then the manager body.

Rules

How the Initializer List Behaves

A few rules govern the initializer list. The base is always initialized first, wherever you write it. Writing it first anyway matches what happens, and reads honestly. Members are initialized in declaration order, not the order you list them. Listing them out of order invites a warning, and a false mental model. Omitting the base call uses its no-argument constructor, and if there's none, it's a compile error. And the body runs last, so anything assigned there is a second write.

Compile Error

Base Without a Default Constructor

Here the base has no no-argument constructor, and the derived constructor says nothing about it. The code won't compile. That's the compiler pointing out you haven't said how to build the base part.

Compiler Warning

Members Listed Out of Order

And here are members listed out of order. The compiler warns, because members are always initialized in declaration order: first, then second, whatever the list says.

Overview

Four Shapes of Hierarchy

There are four shapes of hierarchy. Single inheritance has one base and one derived class. It's the common case, and the one to reach for by default. Multilevel is a chain: C from B, from A. It suits genuine layers of specialization, but keep chains short. Three levels is usually plenty. Hierarchical means several derived classes sharing one base. It's very common: many kinds of one thing. And multiple inheritance gives one class two or more bases. It's occasionally right, and frequently regretted.

Common Mistake

Two Copies of the Device Part

Here's why multiple inheritance needs care. Printer and scanner both derive from device. Now a class derives from both printer and scanner. It would contain two copies of the device part. Two serial numbers, and no answer to which one did you mean. Any reference to an inherited device member is ambiguous, so the code won't compile until the duplication is resolved. Here is the real error. Read the two paths it lists. That shape is the diamond.

Evidence

Sizes Reveal the Diamond Problem

The two copies are real. Printing the sizes shows a device is four bytes, and a copier is eight. Naming the path picks one serial number or the other. C plus plus provides a way to share a single copy instead, which is why the problem has a name: the diamond.

Key Terms

Inheritance Vocabulary Review

A base class is the class being built on, the parent. A derived class builds on it, the child. Is-a is the relationship inheritance expresses. Has-a is the relationship composition expresses. The initializer list is where the base and members get their starting values. Multilevel inheritance is a chain, and multiple inheritance is two or more bases at once. The diamond problem is the duplication when two bases share a base of their own.

Quick Check

Should a Logger Inherit a Stream?

Quick check. A logger class writes timestamped lines to a file. Should it inherit from an output file stream, or hold one as a member? Pause and think. Hold one. A logger isn't a kind of file stream; it uses one. Inheriting would hand every caller the stream's whole interface, raw writes, seeking and closing, all of which bypass the timestamps. As a member, the stream stays private, and the logger exposes only its own log function.

Key Takeaways

Inherit Rarely, Compose by Default

To summarize. A derived class receives the base's data and functions, but not its constructors, destructor or assignment. Inherit only when is-a is true without qualification. Otherwise compose. It promises less, so it changes more easily. The base is built first and destroyed last, and its arguments go in the initializer list. Prefer single inheritance by default. Multiple inheritance brings the diamond.

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 How Child Classes Inherit From Parents

How do I write an inheritance declaration in C++?
Name the base class after a colon in the derived class declaration, for example class manager : public employee { ... };. Manager then contains everything employee has, plus whatever members it adds. The word public keeps the base's public members public to outside code, and it is the usual choice for is-a relationships.
What does a derived class inherit, and what does it not inherit?
A derived class inherits the base's data members and member functions, but not its constructors, destructor, or assignment operator. Those deal with creating, copying, or destroying an object, so they belong to the exact type being made. The derived class supplies its own, and the base's version still handles the base part.
In what order are constructors and destructors called when C derives from B and B derives from A?
Making one C object runs the constructors in the order A, B, C, and destruction runs in reverse: C, B, A. The base part must exist before the derived setup runs, since that setup may use it. The base is also torn down only after the derived cleanup finishes.
How do I pass arguments to a base class constructor, and when should I use composition instead of inheritance?
Put the base constructor call in the derived constructor's initializer list, for example manager(string n, int i) : employee(n, i) { }. The base part is already built by the time the body starts. Use inheritance only when "is-a" is plainly true. If the relationship is "has-a," like a car and its engine, use a member variable.

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 →