Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding virtual specifier in a derived class

Consider following code:

struct virtualfoo 
{
    virtualfoo{};
    virtual ~virtualfoo{};

    virtual double doStuff() = 0
};


struct realbar :  virtualfoo   
{
     realbar{};
     virtual ~realbar{};

     virtual double doStuff();
};

Since I want to implement doStuff() for realbar, virtual isn't mandatory. But if I get this right, it won't hurt to have the virtual specifier next to realbar::doStuff(), does it? What side effects could I get with using/not using virtual?

like image 291
bjoekeldude Avatar asked Jun 12 '26 06:06

bjoekeldude


2 Answers

The virtual keyword is not necessary in the derived class. However it makes code clearer. Also in C++11 override keyword is introduced which allows the source code to clearly specify that a member function is intended to override a base class method.

With keyword override the compiler will check the base class(es) to see if there is a virtual function with this exact signature. And if there is not, the compiler will throws an error.

like image 102
P0W Avatar answered Jun 13 '26 19:06

P0W


It doesn't matter whether you explicitly declare realbar::doStuff as virtual, since it is implicitly virtual due to virtualfoo:doStuff being virtual. So no side effects; realbar::doStuff will be virtual anyway. Confer, for example, this online C++ draft standard:

10.3 Virtual functions

(2) If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref- qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. ...

like image 41
Stephan Lechner Avatar answered Jun 13 '26 18:06

Stephan Lechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!