WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Intermediate · question 35 of 100

How do you prevent a class from being inherited in C++?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

In C++, we can prevent a class from being inherited by declaring it as final. When a class is declared as final, it cannot be used as a base class for any other class. This is useful when we want to prevent unintended modifications to a class’s behavior or implementation.

Here’s an example of how to declare a class as final:

    class Base final {
        // class implementation
    };

In this example, the Base class is declared as final, which means it cannot be inherited by any other class. Any attempt to inherit from Base will result in a compilation error.

It’s important to note that marking a class as final does not prevent the creation of objects of that class. It only prevents inheritance from that class.

    class Base final {
        public:
        void foo() {
            cout << "Base::foo()" << endl;
        }
    };
    
    class Derived : public Base {  // compilation error: Base is final
        public:
        void bar() {
            cout << "Derived::bar()" << endl;
        }
    };
    
    int main() {
        Base b;
        b.foo();  // prints "Base::foo()"
        
        // Derived d;  // compilation error: Base is final
        
        return 0;
    }

In this example, the Base class has a single method foo(), which is accessible from objects of that class. We then try to define a Derived class that inherits from Base, but the attempt results in a compilation error because Base is declared as final.

By using the final keyword, we can ensure that our classes are used as intended and prevent unintended modifications to their behavior or implementation.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics