Rule Definition
Functions overriding virtual functions are always virtual, even if not explicitly declared so. A missing 'virtual' keyword in front of a function overriding virtual functions will hide the polymorphic nature of the function from developers using the it. They may not know that at execution time other functions in the inheritance tree run instead of the function they are reading.
A missing 'virtual' keyword may also be an indication that the author of the function ignored the fact that it needed to be virtual and thus was not aware that the function requires specific attention and specific coding. This usually results in unexpected behavior at runtime which can range from functional bugs to memory leaks and crashes.
Remediation
Add the virtual keyword in the function declaration, checks that the function is implemented as expected and matches the class hierarchy design requirements and documents the function for future extension of the class hierarchy and modification of the function.
Violation Code Sample
class Vehicle
{
public:
Vehicle();
virtual ~Vehicle();
void start();
void stop();
virtual void run();
protected:
Engine* theEngine;
};
class Car : public Vehicle
{
public:
Car();
virtual ~Car();
void run(); // VIOLATION
protected:
int numberOfWheels;
};
Fixed Code Sample
class Car : public Vehicle
{
public:
Car();
virtual ~Car();
virtual void run();
protected:
int numberOfWheels;
};
Reference
High Integrity C++, Rule 3.3.16
Related Technologies
C++
Technical Criterion
Complexity - OO Inheritance and Polymorphism
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.