1. Goals
Recognize the "has-a" relationship expressed by object members.
Use public inheritance only when a derived object can stand in for its base.
Read virtual calls through references and avoid losing the derived part.
2. Prerequisites
You know classes, private members, constructors, destructors, value
copying, and const references. This lesson prepares you for a deeper
look at override and final in C++11. The example uses C++17, like the
rest of this stage.
3. Explanation
StudyCard contains a Label; Label contains a std::string. This is
composition: a card has a label, and a label has a text string.
The members belong to the containing object and are constructed and
destroyed with it according to the rules you already know. The card's
constructor copies the label; it does not borrow a reference to main's
label variable.
A card is not a kind of label, so StudyCard : public Label is unnecessary
just to reuse some text. Start with members when you need to combine data
or coordinate the behavior of several objects.
Reminder : public Notice expresses public inheritance. A reminder
is also a notice and can be used wherever a Notice is needed. render
only needs to call message(); it does not need to check whether the
notice is a reminder. This "is-a" relationship must respect the behavior
the caller expects, not merely reflect a few similar lines of code.
Notice::message() is marked virtual. When a const Notice& refers to
a Reminder, calling this function selects Reminder's implementation.
This is virtual dispatch: behavior depends on the actual object's
type. When the reference refers to a Notice, Notice's implementation
runs. view only borrows reminder; it does not make a copy or extend the
lifetime of that existing object.
override asks the compiler to verify that a function really overrides
a base virtual function. The final const in message() const matters:
removing it does not override Notice's const function. With override,
the mismatch becomes a compilation error. The C++11 lesson on
inheritance, virtual destructors, override, and final
continues this topic.
render accepts const Notice&, preserving the original object. If it
accepted Notice by value, only the Notice part would be copied from
a Reminder; the derived part would be lost. This object slicing
causes calls on that copy to use the base implementation. Use a reference
or pointer for polymorphic access and keep the actual object alive.
Notice has a public virtual destructor: virtual ~Notice() = default;.
In C++17, if you later destroy a Reminder using delete on a Notice*,
the base destructor must be virtual for that destruction to be valid.
This example uses local objects and needs neither new nor delete.
Not every data class needs a virtual destructor; Label and StudyCard
are not polymorphic interfaces. See the
C++ Core Guidelines rule for base destructors.
4. Runnable example
Compile as C++17 and run. All objects are local to main.
#include <iostream>
#include <string>
class Label {
std::string text_;
public:
explicit Label(const std::string& text) : text_(text) {}
const std::string& text() const { return text_; }
};
class StudyCard {
Label label_;
public:
explicit StudyCard(const Label& label) : label_(label) {}
const std::string& title() const { return label_.text(); }
};
class Notice {
public:
virtual ~Notice() = default;
virtual std::string message() const { return "Read one lesson"; }
};
class Reminder : public Notice {
StudyCard card_;
public:
explicit Reminder(const StudyCard& card) : card_(card) {}
std::string message() const override {
return "Review: " + card_.title();
}
};
void render(const Notice& notice) {
std::cout << notice.message() << '\n';
}
int main() {
const Label label("Ownership");
const StudyCard card(label);
const Notice general;
const Reminder reminder(card);
std::cout << "Card: " << card.title() << '\n';
render(general);
render(reminder);
const Notice& view = reminder;
std::cout << "Through reference: " << view.message() << '\n';
return 0;
}Output:
Card: Ownership
Read one lesson
Review: Ownership
Through reference: Review: Ownership5. Common mistakes
Inheriting to reuse a few fields when the "is-a" relationship is wrong.
Omitting
publicfromclass Reminder : public Notice;classinheritance defaults toprivate, preventing outside callers from treating a reminder as aNotice.Removing
virtualfrom the base function but expecting calls through the base type to select the derived implementation.Omitting
constin the derived function, or omittingoverrideand missing the declaration mismatch.Passing the base by value when the derived behavior must be preserved.
Using a reference after the actual object has died, or assuming virtual functions automatically make all resource management correct.
6. Practice
Change the label text to
Lifetime. The three lines naming a topic should change; the general notice staysRead one lesson.Add
DeadlineNotice : public Notice, overridingmessage() constto returnReview before Friday. Pass it torenderwithout changingrender.Try
Notice sliced = reminder;followed byrender(sliced);. ExpectRead one lesson. Compare withrender(reminder)and explain the slicing.Remove
constfromReminder::message()while keepingoverride: compilation must fail. Restoreconstbefore continuing to run the example.
7. Self-check
What relationship connects
StudyCardandLabel, and who owns its label? Answer: a card has a label: composition. The card owns itslabel_member; construction creates an independent copy of the supplied label.Why does
render(reminder)printReview: Ownershipwith a base parameter? Answer: theconst Notice¶meter refers to aReminder, andmessageis virtual. The call selectsReminder's override.What changes if you remove
&fromrender's parameter? Answer: it receives aNoticecopy. When given aReminder, only the base part is copied; the copy is no longer aReminderand uses the general notice implementation.
Sample code
Source file
cpp98_foundation/18_composition_inheritance/main.cpp
#include <iostream>
#include <string>
class Label {
std::string text_;
public:
explicit Label(const std::string& text) : text_(text) {}
const std::string& text() const { return text_; }
};
class StudyCard {
Label label_;
public:
explicit StudyCard(const Label& label) : label_(label) {}
const std::string& title() const { return label_.text(); }
};
class Notice {
public:
virtual ~Notice() = default;
virtual std::string message() const { return "Read one lesson"; }
};
class Reminder : public Notice {
StudyCard card_;
public:
explicit Reminder(const StudyCard& card) : card_(card) {}
std::string message() const override {
return "Review: " + card_.title();
}
};
void render(const Notice& notice) {
std::cout << notice.message() << '\n';
}
int main() {
const Label label("Ownership");
const StudyCard card(label);
const Notice general;
const Reminder reminder(card);
std::cout << "Card: " << card.title() << '\n';
render(general);
render(reminder);
const Notice& view = reminder;
std::cout << "Through reference: " << view.message() << '\n';
return 0;
}