In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
To inherit from a class, use the :
symbol.
In the example below, the Car
class (child) inherits the attributes and methods from the Vehicle
class (parent):
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Try it Yourself »
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!