2

Consider the following little program:

#include <iostream>

class Base {
public:
    virtual void MyFunction() const {
        std::cout << "This is Base" << std::endl;
    }
};

class Derived : public Base {
public:
    virtual void MyFuntcion() {
        std::cout << "This is Derived" << std::endl;
    }
};

int main() {
    Base *p = new Derived();
    p->MyFunction();
    return 0;
}

it compiles cleanly with g++ -Wall -Wextra with nary a peep from the compiler, but when you run it, it prints "This is Base", due to the typo in the function name in Derived.

Now in java or C#, if you put an @override tag on the function, you'll get a warning from the compiler about the typo. Is there any way to do something similar with gcc? Perhaps a magic __attribute__ or some such?

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226

1 Answers1

1

C++11 introduced override as well

class Derived : public Base {
public:
    void MyFuntcion() override {
        std::cout << "This is Derived" << std::endl;
    }
};
test.cpp:12:10: error: 'void Derived::MyFuntcion()' marked 'override', but does not override
     void MyFuntcion() override {
user657267
  • 20,568
  • 5
  • 58
  • 77