Specialization “is-a”(C++)
- One class is a “version” of another class
- Typically subclassing or subtyping relationship
- If B is-a A, then we should be able to substitute something of type B, wherever we expect something of type A.
How is "is-a" implemented?
In C++, achieve specialization via public Inheritance.
class Book {
string title, author;
int length;
protected:
int getLength() const {
return length;
}
public:
Book(string title, string author, int length): title{title}, author{author}, length{length} {}
}
virtual bool isHeavy() const {
return length > 200;
}
}
class Text: public Book {
string topic;
public:
Text(string title, string author, int legnth, string topic): Book{title, author, length}, topic {topic} {}
bool isHeavy() const override {
return getLength() > 500;
}
}
Why Book{title, author, length}
?
Recall the 4 steps of object construction (from Constructor)
- Space is allocated
- Call the superclass constructor
- Initialize fields via a member initialization list (MIL)
- Run the constructor body
We cannot set title, author, length because they are private to book. It will use Books default constructor, won’t compile if default constructor does not exist.