C++ · Module 9 · Lesson 31 min read

Overriding: virtual, override & final

The problem without virtual

arduino
class Shape { public: void draw() const { std::cout << "shape"; } };
class Circle : public Shape { public: void draw() const { std::cout << "circle"; } };

Shape* s = new Circle;
s->draw();   // prints "shape" ❌ — chosen by the POINTER type at compile time

virtual — dynamic dispatch

csharp
class Shape { public: virtual void draw() const; };

Now s->draw() calls the function of the actual object (Circle), decided at runtime. This is runtime polymorphism.

It works through pointers or references to the base class.

override (C++11) ✅

csharp
void draw() const override;
  • Tells the compiler "this must override a base virtual function"
  • If the signature doesn't match (typo, missing const, wrong parameter), you get a compile error instead of a silent new function
  • Always use it

final

  • void draw() const final; — no further overriding allowed
  • class Circle final : public Shape — no class can inherit from Circle

Rules for overriding

  • Same name, parameters and const-ness
  • Return type the same (or a "covariant" derived pointer/reference)
  • virtual is inherited: overrides are virtual too, even without the keyword

Calling the base version

Shape::draw(); from inside the override.

Object slicing ⚠️

Passing a derived object by value as a base copies only the base part → polymorphism is lost:

arduino
void show(Shape s);    // ❌ slices
void show(const Shape& s);   // ✅

Polymorphic containers

c
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2));
for (const auto& s : shapes) s->draw();

Example

C++
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Notification {
public:
    explicit Notification(std::string to) : to_(std::move(to)) {}
    virtual ~Notification() = default;
    virtual std::string channel() const { return "generic"; }
    virtual void send(const std::string& msg) const {
        std::cout << "[" << channel() << "] to " << to_ << ": " << msg << '\n';
    }
    void plain_hello() const { std::cout << "hello from Notification\n"; }   // not virtual
protected:
    std::string to_;
};

class Email : public Notification {
public:
    using Notification::Notification;
    std::string channel() const override { return "email"; }
    void plain_hello() const { std::cout << "hello from Email\n"; }           // hides, doesn't override
};

class Sms final : public Notification {
public:
    using Notification::Notification;
    std::string channel() const override { return "sms"; }
    void send(const std::string& msg) const override {
        Notification::send(msg.size() > 20 ? msg.substr(0, 17) + "..." : msg);   // reuse the base version
    }
    // std::string channel() override { ... }   // error: missing const, override catches it
};

void notify(const Notification& n, const std::string& msg) { n.send(msg); }   // reference: no slicing
void notify_by_value(Notification n, const std::string& msg) { n.send(msg); } // sliced copy

int main() {
    std::vector<std::unique_ptr<Notification>> list;
    list.push_back(std::make_unique<Email>("asha@example.com"));
    list.push_back(std::make_unique<Sms>("9801234567"));
    list.push_back(std::make_unique<Notification>("dashboard"));

    for (const auto& n : list) n->send("Your November budget is 92% used");

    Email e("ravi@example.com");
    Notification& ref = e;
    ref.plain_hello();                 // non-virtual: chosen by the reference type
    e.plain_hello();

    notify(e, "by reference");
    notify_by_value(e, "by value");    // the Email part was sliced off
    return 0;
}

/* Output:
[email] to asha@example.com: Your November budget is 92% used
[sms] to 9801234567: Your November bud...
[generic] to dashboard: Your November budget is 92% used
hello from Notification
hello from Email
[email] to ravi@example.com: by reference
[generic] to ravi@example.com: by value
*/