AutosarC++17_10-A12.1.5

Common class initialization for non-constant members shall be done by a delegating constructor

Required inputs: IR

Rationale

Common initialization of non-constant members in a delegating constructor prevents from code repetition, accidental differences and maintenance problems.

Example
// $Id: A12-1-5.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $

#include <cstdint>

class A {
public:
  // Compliant
  A(std::int32_t x, std::int32_t y) : x(x + 8), y(y) {}
  explicit A(std::int32_t x) : A(x, 0) {}

private:
  std::int32_t x;
  std::int32_t y;
};

class B {
public:
  // Non-compliant
  B(std::int32_t x, std::int32_t y) : x(x + 8), y(y) {}
  explicit B(std::int32_t x) : x(x + 8), y(0) {}

private:
  std::int32_t x;
  std::int32_t y;
};
See Also
  • HIC++ v4.0 [8]: 12.4.5: Use delegating constructors to reduce code duplication.
  • C++ Core Guidelines [10]: C.51: Use delegating constructors to represent common actions for all constructors of a class.

Possible Messages

Key

Text

Severity

Disabled

delegating_constructor

Use delegating constructor for common initialization.

None

False

Options

allow_copy_move_constructor

allow_copy_move_constructor : bool = False

Whether to allow direct field initialization without a delegating constructor call for copy and move constructors.
 

only_report_if_delegate_constructor_exists

only_report_if_delegate_constructor_exists : bool = False

Report violations only if a delegating constructor already exists for the field.
 

only_report_if_more_than_common_field

only_report_if_more_than_common_field : int = 1

Report violations only if constructors initialize at least this many common fields.
 

only_report_if_more_than_constructors

only_report_if_more_than_constructors : int = 1

Report violations only if a field is initialized in more than the given number of constructors.