3

I have written the following program in C++:

class A {
public:
    A() {}
    void foo() { cout << "A::foo" << endl; }
};

class B : public A {
public:
    B() {} 
    void foo() override { cout << "B::foo" << endl; } 
};

For some reason B::foo() does not override the A::foo():

error: ‘void B::foo()’ marked ‘override’, but does not override

Also if I remove the override keyword and run:

int main()
{
    A* a = new B();
    a->foo();
    return 0;
}

It prints: A::foo. Why it does not override?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • Plus one for using `override` to be able to spot errors like this! `A::foo()` is not virtual, so `overide` does not overide. Make `A`'s `foo`: virtual, like: `virtual void foo() { cout << "A::foo" << endl; }` – Ted Lyngmo Jul 05 '19 at 18:46

0 Answers0