MISRA C++:2008 Rule 12-1-2
All constructors of a class should explicitly call a constructor for all of its immediate base classes and all virtual base classes
Description
Rule Definition
All constructors of a class should explicitly call a constructor for all of its immediate base classes and all virtual base classes.
Rationale
Derived classes that do not explicitly call all base class constructors create ambiguity over which base constructor is used during object construction.
Consider this diamond class hierarchy.
SuperClass / \ ClassA ClassB \ / ClassC
When constructing a ClassC
object, it is unclear whether
ClassA
or ClassB
is responsible for initializing the
SuperClass
. If the SuperClass
is constructed with
unintended initial values, then the risk of unexpected code behavior increases. Having
ClassC
explicitly specify the constructor used to initialize the
SuperClass
resolves the diamond ambiguity.
To avoid invalid state and unintended initial values, directly call the necessary base class constructors in the derived class constructor initialization list.
Polyspace Implementation
Polyspace® flags the constructor of a derived class if its initialization list:
Does not explicitly call the constructors of the virtual base classes.
Does not explicitly call the constructors of the direct nonvirtual base classes.
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
Check Information
Group: Special Member Functions |
Category: Advisory |
Version History
Introduced in R2013b