Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Delegating constructors

Use case

Constructors with default values that reuse common initialization.

Explanation

Delegating constructors let one constructor call another using the initializer list syntax : ConstructorName(args). This helps to avoid duplicating initialization code (all paths go through the primary constructor).

Code

#include <cstdint>
#include <iostream>

struct Section {
  uint64_t addr;
  size_t size;
  const char *name;

  // Primary constructor.
  Section(uint64_t a, size_t s, const char *n) : addr(a), size(s), name(n) {
    std::cout << "Created: " << name << " - 0x" << std::hex << addr << " - 0x"
              << std::hex << size << "\n";
  }

  // Delegate (default name).
  Section(uint64_t a, size_t s) : Section(a, s, "__TEXT") {}
};

int main() {
  Section a(0x1000, 0x100, "__DATA");
  Section b(0x2000, 0x200);

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/delegating-constructors
Created: __DATA - 0x1000 - 0x100
Created: __TEXT - 0x2000 - 0x200