Inheritance in C++
Derive new classes from existing ones to reuse code and model "is-a" relationships.
Intermediate
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual ~Shape() = default; // always virtual in a base class
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
private:
double r_;
};
public inheritance means "is-a". Multiple inheritance is allowed but can create the diamond problem, solved with virtual inheritance.
Sub-topics (2)
Virtual Functions and Polymorphism
Call the right derived-class method through a base-class pointer or reference.
Intermediate♥ 0🔖 0💬 0
Abstract Classes
A class with at least one pure virtual function — an interface that can't be instantiated.
Intermediate♥ 0🔖 0💬 0
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.