Search code examples
oopc++11inheritancepolymorphism

Using 'override' keyword


My code gives the following error:

error C3668: 'B::getData': method with override specifier 'override' did not override any base class methods

#include<iostream>
#include <tuple>
using namespace std;

class A {
public:
    int a;

    int getData() {
        return a;
    }
};

class B : public A {
public:
    int b;
    B() {
        b = 100;
    }

    int getData() override {
        return b;
    }
};

int main() {
    B b;
    cout << b.getData() << endl;
}

Why does error occurs and how can I resolve it ??


Solution

  • Your original function in A has to be virtual to be overrided.

    class A {
    public:
        int a;
    
        virtual int getData() {
            return a;
        }
    };
    

    More info about override is here. And related: info on virtual and final