Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor?
#1
The main statement of rule 8-5-1 is:

MISRA C++:2008 Wrote:Each class constructor shall initialize all non-static members of its class.
The example shows a compliant and a non compliant constructor of a class having only member variables of basic numerical type int32_t. It is clear that a member variable of a basic type must be initialized before first read access to avoid an undefined behavior.

But what about non-static members of a class being of type class.

Must a constructor of the class member variable explicitly called in the constructor to be compliant to this rule?

Example:

Code:
class A
{
   public:
      A ( ) : m_a( false )
      {
      }
      bool GetmA ( void )
      {
         return ( m_a );
      }
   private:
      bool m_a;
};


class B
{
   public:
      B ( ) : m_a( false )  // Compliant or non-compliant because of
      {                     // not explicitly calling constructor of m_b?
      }
      B ( const bool a ) : m_a( a ), m_b()  // Definitely compliant
      {
      }
      bool GetmA ( void )
      {
         return ( m_a );
      }
      bool GetmB (void )
      {
          return m_b.GetmA();
      }
   private:
      bool m_a;
      A    m_b;
};

int main ( void )
{
   B b;
   if ( b.GetmB() )
   {
   }
}
The default constructor of class A for member variable m_b is in both constructors of class B called, but in default constructor of class B only implicit according to C++ standard.

Is the default constructor of class B not explicitly calling default constructor of class A for member variable m_b compliant to rule 8-5-1?
Reply
#2
The rule requires that all member objects have defined values before use. As members of class type will be initialised by their constructor, they satisify the rule without explicit initialisation
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#3
Many thanks for that information. That is exactly what we wanted to know and what we thought, too.
Reply
#4
(noted)
Posted by and on behalf of
the MISRA C++ Working Group
Reply


Forum Jump:


Users browsing this thread: 4 Guest(s)