Inheritance
Inheritance allows a class (derived) to acquire members of another class (base).
Use the colon syntax with an access specifier: class Derived : public Base.
Access Specifiers in Inheritance
- public โ public members stay public, protected stay protected.
- protected โ public and protected become protected in the derived class.
- private โ public and protected become private in the derived class.
#include <iostream>
using namespace std;
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Beep beep!\n";
}
};
class Car : public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car car;
car.honk();
cout << car.brand << " " << car.model << "\n";
return 0;
}
Try it Yourself โ