Sub topic 3
Abstract Classes and Pure Virtual Functions
Abstract Classes and Pure Virtual Functions
An abstract class is a class you cannot create objects from directly. It describes what its derived classes must provide. A pure virtual function is a virtual function declared with = 0. A virtual function can select a derived class’s version at runtime.
Save this example as shape.cpp:
#include <iostream>
#include <memory>
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Square : public Shape {
double side_;
public:
explicit Square(double side) : side_(side) {}
double area() const override {
return side_ * side_;
}
};
int main() {
std::unique_ptr<Shape> shape = std::make_unique<Square>(3);
std::cout << shape->area() << '\n';
}Run g++ -std=c++14 shape.cpp -o shape && ./shape. It prints 9.
Square supplies the required area function. The override keyword asks the compiler to check that it matches a base function. The unique_ptr owns the square and deletes it when finished. The virtual destructor makes deletion through the Shape pointer safe.
Name Hiding and Overload Sets
An overload set is a group of functions with the same name but different parameters. If Base has show() and show(int), a derived class that declares its own show() hides the base versions when called through the derived type. Add using Base::show; inside the derived class to make those versions visible.
Virtual Calls During Construction and Destruction
During a base constructor or destructor, a virtual call on the object uses the base-class version, not a more-derived version. Avoid calling a pure virtual function there.
Checked Downcasting
Downcasting means converting a base pointer to a derived pointer. In main, dynamic_cast<Square*>(shape.get()) checks whether the object is a Square. A failed pointer cast returns nullptr, so check the result before using it. The base class must have a virtual function for this check.
Multiple Inheritance and Ambiguity
Multiple inheritance means a class has more than one direct base class. If both bases provide a member with the same name, a call may be ambiguous: C++ cannot choose one. Qualify the name, such as Left::show, to choose a base version.
Diamond Inheritance and Virtual Bases
A diamond occurs when two bases both inherit from the same base. Normally, the final derived object contains two copies of that shared base. If both intermediate classes inherit using virtual, as in struct Left : virtual Base {};, the final object has one shared Base.
Choosing Inheritance or Composition
Use public inheritance when every derived object really is a kind of the base. Composition means putting one object inside another: a car has an engine, for example. Prefer composition when you need a part, not a subtype.
Exercise
What must a class derived from Shape provide before you can create an object of it?
Show answer
It must provide an implementation of the pure virtual area function.