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

Explicit conversion functions

Use case

Safe boolean checks without accidental integer conversion.

Explanation

explicit operator bool() allows if (obj) checks but prevents conversion to int. Without explicit, code like int x = result would compile silently (and might cause bugs).

Code

#include <cstdint>
#include <iostream>

struct AnalysisResult {
  bool valid;
  uint64_t entry;

  explicit operator bool() const { return valid; }
};

int main() {

  AnalysisResult r{true, 0x1000};

  if (r) {
    std::cout << "Valid.\n";
  }

  // no suitable conversion function from "AnalysisResult" to "int" exists
  // int x = r;

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/explicit-conversion-functions
Valid.