Next: 3.2 Constructors and Destructors  Up: 3.1 General  Previous: High Integrity CPP Guideline 3.1.12  Contents

High Integrity CPP Guideline 3.1.13   Verify that all classes provide a minimal standard interface against a checklist comprising: a default constructor; a copy constructor; a copy assignment operator and a destructor.
(QA C++  2110, 2111, 2112, 2114, 2142, 2185, 2610, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2618, 2631, 2632, 2633)

Justification

The following functions are key to making a class behave like a fundamental type and providing for easier comprehension and maintenance.

   
   class X
   {
      X();                      // default constructor
      X( const X& );            // copy constructor 
      X& operator=( const X& ); // copy assignment operator
      ~X();                     // destructor
   };

The compiler will provide default versions for some or all of these functions depending on what user declared versions exist. The behaviour of the compiler-generated default constructor is not always appropriate because it does not initialise members that are of POD type.

The behaviour of the other compiler-generated functions is satisfactory only if a class has no pointer member variables and if each of these implicitly generated functions may have public access.

Defining these functions results in a more consistent interface and a more maintainable and extensible implementation, and carries few penalties. If a class design does not require these functions then explicitly declare them private; this will prevent the compiler generated functions from being used.

Exception

A default constructor is only implicitly generated by the compiler if there is no user-declared constructor.

See also

Rule 3.1.3

Reference

Effective C++ Item 11, 33;Industrial Strength C++ 5.11, 14.2;ISO C++ 12.1/5;


HICPP VERSION 2.4  http://www.codingstandard.com   Copyright: © 2007 THE PROGRAMMING RESEARCH GROUP