Main Content

MISRA C++:2008 Rule 10-3-3

A virtual function shall only be overridden by a pure virtual function if it is itself declared as pure virtual

Description

Rule Definition

A virtual function shall only be overridden by a pure virtual function if it is itself declared as pure virtual.

Rationale

In C++, an abstract class is the base of a polymorphic class hierarchy and the derived classes implement variation of the abstract class. When a virtual function is overridden in a derived class by a pure virtual function, the derived class becomes an abstract class. That a derived class is defined as an abstract class or an implemented function is overridden by a pure virtual function is unexpected behavior, which might confuse a developer.

Polyspace Implementation

Polyspace® flags a pure virtual function if it overrides a function that is not pure virtual.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class Conic{
	//...
	public:
	double centerAbscissa;
	double centerOrdinate;
	//..
	virtual double  getArea()=0;
};
class Circle: public Conic{
	//...
	public:
	//...
	double getArea() override{
		//calculate area of circle
	}
};
class Ellipse: public Circle{
	//...
	public:
	//...
	virtual double getArea()=0; //Noncompliant
};

In this example, the base class Conic is an abstract class because the function getArea() is a pure virtual function. The derived class Circle implements the function getArea. The expectation from such a polymorphic hierarchy is that the virtual function getArea calculates the area correctly based on the derived class. When the derived class Ellipse redeclares getArea as a pure virtual function, the derived class Ellipse becomes abstract and the function Ellipse.getArea() cannot be invoked. Developers might expect Ellipse.getArea() to return the area of the ellipse. Because this redeclaration as a pure virtual function does not meet developer expectation, Polyspace flags the declaration.

Check Information

Group: Derived Classes
Category: Required

Version History

Introduced in R2013b