Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@overrides for C++?

Tags:

c++

Is there a way in C++ to ensure that a virtual method in a subclass is in fact overriding a super class virtual method? Sometimes when I refactor, I forget a method and then wonder why it is not being called but I forgot to change the method signature so it is no longer overriding anything.

Thanks

like image 480
jmasterx Avatar asked May 21 '12 18:05

jmasterx


People also ask

Is overriding possible in C?

Master C and Embedded C Programming- Learn as you goThe function overriding is the most common feature of C++. Basically function overriding means redefine a function which is present in the base class, also be defined in the derived class. So the function signatures are the same but the behavior will be different.

Is override needed C++?

You don't need the override identifier to do this in C++, it simply enforces that you are doing it properly.

What is overriding in C?

Function overriding is a concept in object-oriented programming which allows a function within a derived class to override a function in its base class, but with a different signature (and usually with a different implementation).

What is meant by override in C++?

Function overriding is a redefinition of the base class function in its derived class with the same signature i.e. return type and parameters.


1 Answers

It is possible in C++11, with the override identifier:

struct Base {    
  virtual void foo() const { std::cout << "Base::foo!\n"; }
};

struct Derived : virtual public Base {
  virtual void foo() const override {std::cout << "Derived::foo!\n";}
};

This allows you to find out at compile time whether you are failing to override a method. Here, we neglect to make the method const:

struct BadDerived : virtual public Base {
  virtual void foo() override {std::cout << "BadDerived::foo!\n";} // FAIL! Compiler finds our mistake.

};
like image 83
juanchopanza Avatar answered Oct 11 '22 08:10

juanchopanza