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

Asked

Viewed 216 times

4

When I was learning C++ I read in a book in the polymorphism chapter about virtual functions that the virtual keyword was meant to indicate that that function was going to be overwritten in another part of the code, since then I started adding virtual in all my header settings.

One day I was in an android studio project where I used NDK, when I received an error similar to this:

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

Searching about 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 of a Unreal engine 4 project that was not overwritten from another class, so using virtual functions in non-derivative classes is correct or just ignored by desktop compilers? (Note: I use MSVC, I don’t remember this error in g++ either, android studio uses Clang)

  • "since then I started adding virtual in all my header settings" - this sounds like abuse of functionality, use without reason.

1 answer

2


As you said yourself, using virtual keyword serves to indicate that the function can be overwritten in another part of the code. So, if you are using the class in a polyformic way, that is, if you are using a pointer or reference type of the base class 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 the Base class does not have a virtual destructor, the destructor that is called is the Base class, leaving the Foo class part undone, and then we enter the world of undefined behavior. So as a rule, if a class provides some virtual function (which means it can be inherited) it must also provide a virtual destructor.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.