Explicit Constructor in C++

Level 5505 keystrokes

An explicit constructor cannot be used for implicit conversions, so processUser(42) would not compile and a UserId must be created explicitly. Score has a normal constructor, so processScore(100) converts 100 to a Score automatically.

C++ code

1class UserId {
2 int value;
3public:
// explicit: an int is not converted to UserId automatically
4 explicit UserId(int v) : value(v) {}
5 int get() const { return value; }
6};
7
8class Score {
9 int value;
10public:
// Not explicit: allows implicit conversion from int to Score
11 Score(int v) : value(v) {}
12 int get() const { return value; }
13};
14
// Take the wrapper types as parameters
15void processUser(UserId id) { cout << "User: " << id.get() << endl; }
16void processScore(Score s) { cout << "Score: " << s.get() << endl; }
17
// The UserId is created explicitly
18UserId user(42);
// Prints "User: 42"
19processUser(user);
// 100 is converted to Score implicitly: prints "Score: 100"
20processScore(100);
21
// Only text: processUser(42) itself would be a compile error
22cout << "UserId prevents: processUser(42)" << endl;
23cout << "Score allows: processScore(100)" << endl;

Output

User: 42
Score: 100
UserId prevents: processUser(42)
Score allows: processScore(100)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 20
  • (× 15
  • )× 15
  • ;× 13
  • :× 8
  • "× 8
  • {× 8
  • }× 8
  • .× 2

More C++ examples at level 5

← C++ typing practice