Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing 'virtual' qualifier in function declarations

Whilst trawling through some old code I came across something similar to the following:

class Base
{
public:
    virtual int Func();
    ...
};

class Derived : public Base
{
public:
    int Func(); // Missing 'virtual' qualifier
    ...
};

The code compiles fine (MS VS2008) with no warnings (level 4) and it works as expected - Func is virtual even though the virtual qualifier is missing in the derived class. Now, other than causing some confusion, are there any dangers with this code or should I change it all, adding the virtual qualifier?

like image 237
Rob Avatar asked Dec 17 '22 09:12

Rob


2 Answers

The virtual will be carried down to all overriding functions in derived classes. The only real benefit to adding the keyword is to signify your intent a casual observer of the Derived class definition will immediately know that Func is virtual.

Even classes that extend Derived will have virtual Func methods.

Reference: Virtual Functions on MSDN. Scroll down the page to see

The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual.

like image 177
Blair Conrad Avatar answered Dec 31 '22 15:12

Blair Conrad


Here's an interesting consequence of not needing to declare overriding functions virtual:

template <typename Base>
struct Derived : Base
{
    void f();
};

Whether Derived's f will be virtual depends on whether Derived is instantiated with a Base with a virtual function f of the right signature.

like image 45
James Hopkin Avatar answered Dec 31 '22 16:12

James Hopkin