C++ Inheritance
Inheritance is a way for one class to build on another class. The new class gains the members and methods of the class it builds on.
Using a base class method
Car builds on Vehicle. Car calls the drive method from Vehicle without writing it again.
#include <iostream>
class Vehicle {
public:
void drive() {
std::cout << "The vehicle drives" << std::endl;
}
};
class Car : public Vehicle {
};
int main() {
Car car;
car.drive();
return 0;
}Adding a method of its own
Car adds a honk method of its own. The main function calls the base method first and the added method second.
#include <iostream>
class Vehicle {
public:
void drive() {
std::cout << "The vehicle drives" << std::endl;
}
};
class Car : public Vehicle {
public:
void honk() {
std::cout << "Beep" << std::endl;
}
};
int main() {
Car car;
car.drive();
car.honk();
return 0;
}Reading a protected member
The brand member sits under protected: in Vehicle. Members under protected: are open to classes built on Vehicle and closed to the rest.
#include <iostream>
#include <string>
class Vehicle {
protected:
std::string brand = "Ford";
};
class Car : public Vehicle {
public:
void showBrand() {
std::cout << brand << std::endl;
}
};
int main() {
Car car;
car.showBrand();
return 0;
}Example
#include <iostream>
#include <string>
class Vehicle {
protected:
std::string brand = "Ford";
public:
void describe() {
std::cout << "Brand: " << brand << std::endl;
}
};
class Car : public Vehicle {
public:
int wheels = 4;
};
int main() {
Car car;
car.describe();
std::cout << "Wheels: " << car.wheels << std::endl;
return 0;
}Key points
- A base class is a class that another class builds on.
- A derived class is a class built on a base class.
- The line class Car : public Vehicle makes Car a derived class of Vehicle.
- A derived class can use a public method of its base class without writing it again.
- A derived class can add methods of its own.
- Members under protected: are open to classes built on the class and closed to the rest.
In this example, Vehicle holds the brand member and the describe method. Car builds on Vehicle and adds the wheels member. The program prints the brand line first and the wheels line second.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What does the line class Car : public Vehicle do?