Module lessons (2/2)
Polymorphism and virtual functions
Polymorphism allows us to treat objects of different derived classes through a pointer or reference to their base class, ensuring the correct version of a method is called at runtime (Late Binding).
Virtual Functions: virtual and override
To enable polymorphism on a method, we must declare it using the virtual keyword inside the base class. In derived classes, we use the override specifier to explicitly state that we are overriding that method.
class Employee {
public:
virtual void work() {
std::cout << "Generic work" << std::endl;
}
// IMPORTANT: Virtual destructor in base class to avoid memory leaks
virtual ~Employee() = default;
};
class Developer : public Employee {
public:
void work() override {
std::cout << "Writing C++ code" << std::endl;
}
};
Using pointers to the base class, C++ will resolve the correct method at runtime:
Employee* emp = new Developer();
emp->work(); // Prints "Writing C++ code" instead of "Generic work"
delete emp;
Abstract Classes and Pure Virtual Functions
A pure virtual function is a virtual member function declared with = 0 at the end. It represents a formal contract: the base class provides no implementation, delegating it entirely to subclasses.
A class containing at least one pure virtual function is called an Abstract Class and cannot be instantiated directly.
class Instrument {
public:
virtual void play() = 0; // Pure virtual
virtual ~Instrument() = default;
};
class Piano : public Instrument {
public:
void play() override {
std::cout << "Playing piano..." << std::endl;
}
};
Try it yourself
Define a virtual method makeSound() in Animal that prints 'Some sound'. Then override it in the Cat class using the override specifier to print 'Meow'.
Show hint
Remember to prepend `virtual` to the base class method and place `override` after the parameter parentheses in the derived class.
Solution available after 3 attempts
Declare a pure virtual function print() returning void within the abstract class Printable. Then create the Document class that publicly inherits from Printable and implements the print() method to print 'Printing Document'.
Show hint
A pure virtual function is declared with the signature `virtual void print() = 0;`. Ensure `Document` inherits publicly from `Printable`.
Solution available after 3 attempts