C++11 override and final

beginner
21 min

C++11 override and final

Welcome to this comprehensive guide on C++11's override and final keywords! We'll explore these powerful tools that will help you write cleaner, more maintainable code. Let's dive in!

Overview

šŸŽÆ C++11 introduces override and final to improve the readability, maintainability, and polymorphism capabilities of your code.

Virtual Functions and Polymorphism

šŸ“ Before we delve into override and final, it's crucial to understand virtual functions and polymorphism. Polymorphism allows objects of different classes to be treated as objects of a common base class.

The override Keyword

šŸ’” Pro Tip: Use override to declare an overriding function and ensure that it matches the base class's function signature.

cpp
// Base class class Base { public: virtual void print() { std::cout << "Base class"; } }; // Derived class with an overriding function class Derived : public Base { public: void print() override { // Overriding function std::cout << "Derived class"; } };

The final Keyword

šŸ’” Pro Tip: Use final to prevent a function or a class from being overridden, ensuring that it cannot be modified in derived classes.

cpp
// Base class with a final function class Base { public: void print() final { // Final function std::cout << "Base class"; } }; // Derived class trying to override a final function (compiler error) class Derived : public Base { public: void print() { // Compiler error: 'print' is marked as final std::cout << "Derived class"; } };

Quiz

Quick Quiz
Question 1 of 1

Which of the following statements best describes the `override` keyword in C++?

Advanced Examples

šŸ“ Note: Advanced examples will demonstrate best practices and real-world scenarios where override and final are used effectively.

cpp
// Base class class Shape { public: virtual double area() const = 0; // Pure virtual function virtual void draw() const = 0; // Pure virtual function }; // Derived class implementing the area function class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double area() const override { // Overriding area function return 3.14159 * radius * radius; } void draw() const override { // Overriding draw function std::cout << "Drawing a circle with radius " << radius << ".\n"; } }; // Derived class with a final function class Square : public Shape { private: double side; public: Square(double s) : side(s) {} double area() const final { // Final area function return side * side; } void draw() const override { // Overriding draw function std::cout << "Drawing a square with side " << side << ".\n"; } };

Conclusion

šŸŽÆ With a firm grasp of C++11's override and final keywords, you'll be able to write more maintainable, polymorphic code. Happy coding!