Main Content

MISRA C++:2023 Rule 8.2.9

The operand to typeid shall not be an expression of polymorphic class type

Since R2024b

Description

Rule Definition

The operand to typeid shall not be an expression of polymorphic class type.

Rationale

Using expressions of polymorphic class types as operands to typeid operator can lead to unpredictable run time behavior or exception:

  • Whether the compiler evaluates the expression at run time is uncertain. If the expressions have side effect, then the behavior of the code at run time can become unpredictable.

  • Evaluating the expression can lead to dereferencing of nullptr and an exception of std::bad_typeid

This rule applies even if your code performs no runtime evaluation of the typeid operands. The rule does not apply if you do not use expressions of a polymorphic class type as operands to typeid (type-id):

std::type_info const& type(typeid(std::iostream)); // Rule does not apply
Here, std::iostream is not an instance of a polymorphic class. Because the operand of typeid is not an expression of polymorphic class types, such use of the typeid operator is not a violation of this rule.

Polyspace Implementation

Polyspace® reports a violation of this rule if you use an expression of polymorphic class type as the operand to the typeid operator. A polymorphic class is a class that contains or inherits at-least one virtual function.

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

This example shows compliant and noncompliant use of the typeid operator.

#include <typeinfo>

class Polymorphic {
	// Class contains at least one virtual function
	virtual void func() {}
};
class NonPolymorphic {
	void func();
};

const std::type_info& foo(Polymorphic &pm) {
	std::type_info const &t1 = typeid(Polymorphic);     // Compliant
	std::type_info const &t2 = typeid(pm.func());       // Compliant
	return typeid(pm);                                  // Noncompliant
}

const std::type_info& bar(NonPolymorphic &npm) {

	return typeid(npm);                                 // Compliant
}

  • The operation typeid(pm) is a violation of this rule because pm is an expression of a polymorphic class type.

  • The operation typeid(Polymorphic) is not a violation because Polymorphic is not an expression of a polymorphic class type.

  • The operation typeid(pm.func()) is not a violation because pm.func() refers to the return type of a specific instance of a member function. The type of pm.func() is known and it is always void.

  • The operation typeid(npm) is not a violation of this rule because npm is an instance of class NonPolymorphic, which is not a polymorphic class.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2024b