ProblemsUB & GotchasThe connection that equals five
NoviceUB & Gotchas

The connection that equals five

Context

The dashboard showed "6 connections" where there was one. Someone wrote conn + 5, the compiler turned the connection into 1 — and the code compiled without a single warning. The class allows the bool conversion to happen implicitly, anywhere.

Task

The class converts to bool on its own, so even conn + 5 compiles. Add one keyword so that if (conn) still works, but arithmetic with a connection no longer compiles.

Constraints

  • if (conn), while (conn) and !conn must still work (contextual conversion)
  • conn + 1, int x = conn and bool b = conn must NOT compile
  • Do not remove the conversion operator or add a separate isOpen() workaround
  • Keep the rest of the class unchanged

Before you code

  • Why does an implicit operator bool make conn + 5 legal?
  • What exactly does explicit allow in an if condition that it forbids elsewhere? (contextual conversion)
  • Why is explicit operator bool the idiom in every serious codebase (streams, smart pointers)?

Tests

  • #1if / while / ! still work
  • #2An explicit cast is still available
  • #3Arithmetic with a connection does not compile(expects compile error)
  • #4Copy-initializing a bool does not compile(expects compile error)

Hints

Hint 1

You do not need to forbid the conversion — only to stop it from happening implicitly. One keyword on the operator does it.

Hint 2

An explicit operator bool is still used automatically in if, while, ! and && — the standard calls this "contextual conversion".

Editorimplicit-bool-conversion.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.