Direct naar de hoofdinhoud
eLearner.app
Module 6 · Les 2 van 214/18 in de cursus~15 min
Modulelessen (2/2)

Polymorfisme en virtuele functies

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.

Code
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:

Code
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.

Code
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

Oefening#cpp.m6.l2.e1
Pogingen: 0Laden…

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'.

Editor laden…
Toon hint

Remember to prepend `virtual` to the base class method and place `override` after the parameter parentheses in the derived class.

Oplossing beschikbaar na 3 pogingen

Oefening#cpp.m6.l2.e2
Pogingen: 0Laden…

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'.

Editor laden…
Toon hint

A pure virtual function is declared with the signature `virtual void print() = 0;`. Ensure `Document` inherits publicly from `Printable`.

Oplossing beschikbaar na 3 pogingen