final


Keyword: final

In C++, the final keyword is used to prevent further inheritance or overriding. It can be applied in two main contexts: - Preventing Class Inheritance: When applied to a class, final indicates that the class cannot be derived from. - Preventing Method Overriding: When applied to a virtual function in a base class, final indicates that the function cannot be overridden by derived classes.

Example 1: final with Classes

When you mark a class as final, it cannot be used as a base class for any other class. This is useful when you want to design a class that should not be extended.

#include <iostream>

class Base final {
public:
    void display() {
        std::cout << "Base class display function" << std::endl;
    }
};

// This will cause a compile-time error
// class Derived : public Base {
// };

int main() {
    Base b;
    b.display();

    return 0;
}

Explanation

The Base class is marked as final, so any attempt to derive another class from Base (like the commented Derived class) will result in a compile-time error. This ensures that Base cannot be used as a base class for any other class.

Exapmle 2: final with Virtual Functions

When applied to a virtual function, final prevents that function from being overridden in derived classes. This is useful when you want to lock down the implementation of a virtual function in a specific class.

#include <iostream>

class Base {
public:
    virtual void show() final {
        std::cout << "Base class show function" << std::endl;
    }
};

class Derived : public Base {
public:
    // This will cause a compile-time error
    // void show() override {
    //     std::cout << "Derived class show function" << std::endl;
    // }
};

int main() {
    Derived d;
    d.show();  // Calls Base::show()

    return 0;
}

Explanation

The show function in the Base class is marked as final. This means it cannot be overridden by any class that derives from Base. Attempting to override show in the Derived class (as shown in the commented code) will result in a compile-time error. In the main function, calling d.show() will invoke the Base::show method because the override attempt is disallowed.

Summary

Using final is a way to enforce design constraints, ensuring that certain classes or methods cannot be altered by subclassing or overriding, which can help maintain a stable and predictable class hierarchy.

Previous Page | Course Schedule | Course Content