MISRA Discussion Forums
Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19)
+---- Forum: 6.8 Declarators (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=137)
+---- Thread: Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor? (/showthread.php?tid=1322)



Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor? - ProgCPlusPlus - 07-03-2017

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?


Re: Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor? - misra cpp - 10-07-2017

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


Re: Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor? - ProgCPlusPlus - 10-07-2017

Many thanks for that information. That is exactly what we wanted to know and what we thought, too.


Re: Rule 8-5-1 Must a non-static class member variable also explicitly initialized in constructor? - misra cpp - 17-01-2018

(noted)