Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override keyword throwing an error while compile

I have base class

template<typename T>
Class Base {
  Base();

public:
  virtual void myfunc()=0; 
}

I have derived class

template<typename T>
Class Derived: public Base<T> {
  Derived():Base() {
  }

public:
  void myfunc() override; 
}

When I compile g++ -std=c++0x, I get the error with the overriding function highlighted, error: expected ‘;’ at end of member declaration error: ‘override’ does not name a type

g++ version is 4.6.

like image 934
user592748 Avatar asked Apr 02 '13 23:04

user592748


People also ask

What does the override keyword do?

The override keyword serves two purposes: It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class." The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

What does override function do in C++?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

What is a override specifier in C++?

Explanation. In a member function declaration or definition, override specifier ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.

Why is overriding necessary in C++?

Overriding in C++ is one of the ways to achieve run time polymorphism, in which we modify the behavior of the same method. In general, the child class inherits the member functions and data members from the base class.


2 Answers

override keyword is not supported by GCC 4.6. If you want to override myfunc, just delete override keyword or upgrade GCC to 4.7 version. (Ref: https://blogs.oracle.com/pcarlini/entry/c_11_tidbits_explicit_overrides)

like image 67
haitaka Avatar answered Oct 10 '22 02:10

haitaka


g++ 4.6.3 doesn't support the override feature of C++11. When you take away the syntatical errors, this code compiles fine in 4.7.2 and Clang.

Moreover, I think this is what you meant your code to be:

template <typename T>
class Base {
   Base();

   public:
      virtual void myfunc() = 0; 
};

template <typename T>
class Derived : public Base<T> {
   Derived() : Base<T>() {}

   public:
      void myfunc() override;
};
like image 32
David G Avatar answered Oct 10 '22 00:10

David G