Inheritance: reusing and specializing classes
Inheritance lets you create a new class from an existing one. The derived class receives the members of the base class and can add others or change their behavior. It is the way to express an "is a" relationship: an Employee is a Person, a Manager is an Employee. When that relationship exists, inheritance avoids duplicating code and allows treating different objects uniformly. But careful: you do not inherit only to reuse code. If the relationship is not really "is a" (a Stack is not a vector), it is better to use composition, that is, to store the other object as a member.
Syntax and access levels
It is written class Derived : public Base { ... };. The word public indicates public inheritance, the one that expresses "is a" and the one you will use almost always. The private members of the base exist in the object, but the derived class cannot access them. To share with child classes without exposing to the outside there is protected, although it should be used sparingly: it is better to keep data private and offer protected or public methods. A key detail is construction: the base part is built first and then the derived part, and they are destroyed in reverse order. If the base needs arguments, the derived class must pass them in its initializer list.
#include <iostream>
#include <string>
#include <utility>
class Person {
public:
Person(std::string name, int age) : name_{std::move(name)}, age_{age} {
std::cout << "Person created\n";
}
~Person() { std::cout << "Person destroyed\n"; }
const std::string& name() const { return name_; }
int age() const { return age_; }
std::string describe() const {
return name_ + " (" + std::to_string(age_) + ")";
}
private:
std::string name_;
int age_;
};
class Employee : public Person {
public:
Employee(std::string name, int age, double salary)
: Person{std::move(name), age}, salary_{salary} { // base first
std::cout << "Employee created\n";
}
~Employee() { std::cout << "Employee destroyed\n"; }
double salary() const { return salary_; }
// hides Person::describe with a new version for this class
std::string describe() const {
return Person::describe() + ", salary " + std::to_string(static_cast<int>(salary_));
}
private:
double salary_;
};
int main() {
Employee e{"Ana", 30, 2500.0};
std::cout << e.describe() << '\n';
// Person created
// Employee created
// Ana (30), salary 2500
// Employee destroyed
// Person destroyed
return 0;
}Hiding is not overriding
In the example, Employee::describe hides Person::describe: when you call describe on an Employee the new version is used, and if you need the old one you invoke it with Person::describe(). But this mechanism works only when the compiler knows the exact type of the object. If you had a Person* pointing to an Employee and called describe, Person's version would run, because the function is not virtual. Solving this is the topic of the next lesson: polymorphism with virtual functions. For now remember that hiding and overriding are different things.
#include <iostream>
#include <string>
#include <utility>
class Shape {
public:
explicit Shape(std::string name) : name_{std::move(name)} {}
const std::string& name() const { return name_; }
protected:
// derived classes may use it, outside code may not
double scale(double value) const { return value * 2.0; }
private:
std::string name_;
};
class Square : public Shape {
public:
explicit Square(double side) : Shape{"square"}, side_{side} {}
double doubledArea() const { return scale(side_ * side_); } // protected is usable here
private:
double side_;
};
int main() {
Square s{3.0};
std::cout << s.name() << ' ' << s.doubledArea() << '\n'; // square 18
// s.scale(1.0); // error: 'scale' is protected
return 0;
}A frequent mistake: using inheritance only to reuse a function. If a Logger class has a log method and you inherit from it to be able to call log in your Server class, you are saying that "a Server is a Logger", which is false. The solution is composition: Server has a Logger member. Another practical rule is to prefer short hierarchies, of one or two levels. Deep hierarchies become hard to understand because to know what a method does you must walk up several classes.
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字