Use of virtual for Init() instead of override?

Hello,

I know this might be a bit pedantic, but would it not be better to use override in the derived class for the Init() function instead of virtual?
I think it comes down to the same thing, is this more of a stylistic choice or is there an actual difference?

virtual means that this function can be overridden in child class. override is just security because it does not allow you to compile if you are not overriding anything.

So the code works without virtual or override. But it’s good to add both of them for readability and security.

There’s a good description of what override does here: override specifier (since C++11) - cppreference.com

Also for virtual: virtual function specifier - cppreference.com

To summarise, override indicates that the method is overriding a base class method and that method is declared as virtual. It is optional BUT if the signatures for the overriding method doesn’t match, it can introduce a bug in your code and adding override can highlight the bug during compile.

Edit: some sample code below. Removing override works - the calls to hello both print out hello and hello world. if you take virtual out, and leave override, compile fails. If you take out both virtual and override, the program still works but b.Hello() doesn’t print Hello World like it does when virtual is present. I’ve attached the screenshot of the results of this test.

#include <iostream>

class BaseTest
{
public:
  virtual void Hello();
};

class InheritTest : public BaseTest
{
public:
  void Hello() override;
};


void BaseTest::Hello()
{
  std::cout << "Hello!\n";
}

void InheritTest::Hello()
{
  BaseTest::Hello();
  std::cout << "Hello World!\n";
}


int main()
{
  std::cout << "Inheritance experiments\n";
  InheritTest c;
  BaseTest& b =c;
  c.Hello();
  b.Hello();
}

Personally in my code I follow the guideline of using only one of virtual or override in a declaration.

The CppCoreGuidelines gives a good explanation of why
C++ Core Guidelines

However with Unreal I do add virtual as it seems to be their style (also I’m too lazy to constantly delete them from generated code … even though I probably spend more time adding virtual to new declarations for consistency)

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.