Anand Kumar Sinha
Anand Kumar Sinha

Reputation: 149

virtual function declared non-virtual in a derived class

If a function is declared non-virtual in a derived class when the base class function was virutal, why does it invoke a vtable lookup on calling the function on its pointer? The function is clear from the scope.

Upvotes: 13

Views: 3040

Answers (5)

6502
6502

Reputation: 114599

In C++ if you declare a method virtual in the base class then it's virtual also in derived class, even if the virtual keyword is omitted.

For documentation purposes is however in my opinion nice to repeat it anyway.

Upvotes: 21

masoud
masoud

Reputation: 56549

Virtual methods created to affect on derived class (When you mark a method as virtual. It will use vtable on derived classes). And the overrided methods will be virtual.

Upvotes: 1

Janick Bernet
Janick Bernet

Reputation: 21214

You cannot make a function non-virtual, so it will stay virtual and a call to the function is in general also virtual. Of course, there are situations where the compiler will be able to optimize this and do a direct call, but apparantly not in your scenario.

Upvotes: 5

PlasmaHH
PlasmaHH

Reputation: 16046

The function is still virtual (assuming it has the same or a covariant signature). Using virtual when overriding is redundant.

Upvotes: 2

Nate
Nate

Reputation: 12849

When a class inherits a virtual function, any new, overriding declaration of that function will automatically be made virtual, even if the virtual keyword is not used.

Upvotes: 0

Related Questions