Basic Inheritance
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 48 of 104.
Inheritance allows a class to acquire the properties and behaviors of another class. The class being inherited from is called the base class (or parent), and the class that inherits is called the derived class (or child).
To create a derived class, use a colon followed by the access specifier and base class name:
class Animal {
public:
std::string name;
void eat() {
std::cout << name << " is eating" << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << name << " says woof!" << std::endl;
}
};The Dog class now has access to both name and eat() from Animal, plus its own bark() method. This is the essence of inheritance: reusing existing code while adding new functionality.
Dog myDog;
myDog.name = "Buddy";
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in DogThe public keyword before Animal specifies the inheritance type. Public inheritance means public members of the base class remain public in the derived class. This is the most common form and models an "is-a" relationship: a Dog is an Animal.
Challenge
EasyLet's build a simple vehicle hierarchy that demonstrates inheritance in action. You'll create a base Vehicle class and a derived Motorcycle class that extends it with specialized behavior.
You'll organize your code across three files:
Vehicle.h: Define a baseVehicleclass with:- A public
std::string brandmember - A public
int yearmember - A public method
displayInfo()that prints the vehicle's brand and year in the format:Brand: <brand>, Year: <year>
- A public
Motorcycle.h: Define aMotorcycleclass that publicly inherits fromVehicle. This derived class should add:- A public
int engineCCmember for the engine displacement - A public method
revEngine()that prints:<brand> goes vroom vroom!
The
Motorcycleclass will automatically inheritbrand,year, anddisplayInfo()fromVehicle.- A public
main.cpp: Read three inputs (each on a separate line):- Brand name (string)
- Year (integer)
- Engine CC (integer)
Create a
Motorcycleobject, set its inherited members (brandandyear) as well as its ownengineCCmember. Then demonstrate inheritance by calling both the inherited method and the motorcycle-specific method.Output format:
Brand: <brand>, Year: <year> Engine: <engineCC>cc <brand> goes vroom vroom!
For example, with inputs Harley, 2022, and 1200:
Brand: Harley, Year: 2022
Engine: 1200cc
Harley goes vroom vroom!Don't forget to include header guards in your header files and use #include "Vehicle.h" in your Motorcycle header to access the base class.
Cheat sheet
Inheritance allows a class to acquire properties and behaviors from another class. The class being inherited from is the base class (parent), and the class that inherits is the derived class (child).
To create a derived class, use a colon followed by the access specifier and base class name:
class Animal {
public:
std::string name;
void eat() {
std::cout << name << " is eating" << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << name << " says woof!" << std::endl;
}
};The derived class has access to public members of the base class plus its own members:
Dog myDog;
myDog.name = "Buddy";
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in DogThe public keyword specifies public inheritance, meaning public members of the base class remain public in the derived class. This models an "is-a" relationship.
Try it yourself
#include <iostream>
#include <string>
#include "Motorcycle.h"
using namespace std;
int main() {
string brand;
int year;
int engineCC;
cin >> brand;
cin >> year;
cin >> engineCC;
// TODO: Create a Motorcycle object
// TODO: Set its brand, year, and engineCC members
// TODO: Call displayInfo() to show inherited info
// TODO: Print the engine info in format: Engine: <engineCC>cc
// TODO: Call revEngine() to demonstrate motorcycle-specific behavior
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container