Is it a good practice to use virtual functions in non-derived classes?

3
When I was learning C ++ in a book on the polymorphism chapter on virtual functions, that the virtual keyword served to indicate that that function was going to be overwritten in another part of the code, since then I've added virtual in all my definitions header.

One day I was in an android studio project where I used NDK, how much I got an error similar to this:

  

The class has virtual functions, but does not have a destructor   virtual

Searching for this error I soon noticed that people only used the virtual keyword in derived or abstract classes, but I soon remembered seeing a virtual function in a class from an unreal engine 4 project that was not overwritten by another class, so using virtual functions in non-derived classes is correct or just ignored by desktop compilers? (Note: I use MSVC, I do not remember this error in g ++ also, android studio uses clang)

    
asked by anonymous 27.06.2018 / 19:13

1 answer

1

As you yourself said, using virtual keyword is meant to indicate that the function can be overwritten elsewhere in the code. So if you are using the class in a poliform way, that is, if you are using a pointer or reference of the base class type to access that function the program will look for the correct function to be called at runtime. For example:

class Base{
  public:
  virtual void f();
  ~Base();
};

class Foo:
  public Base
{
  ...  //outras declarações
  public:
  void f();
  ~Foo();
};

int main(){
    Base* base = new Foo();
    base->f();  //chama a função f na classe Foo
    delete base;//chama o destrutor de Base 
}
Since the function Base class does not have a virtual destructor, the destructor that is called is Base, leaving the Foo class part to be destroyed, and then we enter the world of undefined behavior. So by rule, if a class provides some virtual function (which means that it can be inherited) it must also provide a virtual destructor.

And so you may wonder, why in% with% all member function calls are not determined at runtime without the need to declare them as virtual? The simplest answer has to do with the fact that the process is a little painful ( link to a more detailed explanation in English ).

    
27.06.2018 / 21:33