Rule A12-1-1 (required, implementation, automated)
Constructors shall explicitly initialize all virtual base classes, all direct non-virtual base classes and all non-static data members.
Rationale
A constructor of a class is supposed to completely initialize its object. Explicit initialization of all virtual base classes, direct non-virtual base classes and non-static data members reduces the risk of an invalid state after successful construction.
Example
// $Id: A12-1-1.cpp 271696 2017-03-23 09:23:09Z piotr.tanski $
#include <cstdint>
class Base
{
// Implementation
};
class VirtualBase
{
};
class A : public virtual VirtualBase, public Base
{
public:
A() : VirtualBase{}, Base{}, i{0}, j{0} // Compliant
{
}
A(A const& oth)
: Base{}, j{0}
//
//
Non-compliant - VirtualBase base class and member
i not initialized
{
}
private:
std::int32_t i;
std::int32_t j;
static std::int32_t k;
};
std::int32_t A::k{0};
See also
MISRA C++ 2008 [7]: 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.
HIC++ v4.0 [9]:12.4.2 Ensure that a constructor initializes explicitly all base classes and non-static data members. JSF December 2005 [8]: AV Rule 71: Calls to an externally visible operation of an object, other than its constructors, shall not be allowed until the object has been fully initialized.