Search⌘ K
AI Features

Discussion: A Strong Point

Explore the concept of strong typing in C++ through the Player and Points example. Understand how direct and copy initialization differ, and why marking single-argument constructors as explicit helps avoid subtle bugs. Learn to use strong types for clearer, safer code and how implicit conversions work in constructor calls.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
struct Points
{
Points(int value) : value_(value) {}
int value_;
};
struct Player
{
explicit Player(Points points) : points_(points) {}
Points points_;
};
int main()
{
Player player(3);
std::cout << player.points_.value_;
}

Strong typing

The Player struct has a points_ member to keep track of the player’s points. Instead of using a fundamental type like int for this, we use a custom type Points ...