Type Safety & Type Conversion Practices in C++

“The ideal is never to use language features that the compiler cannot prove to be safe”

Gulshan
2 min readJul 21, 2022

Type :- “A type defines a set of possible values and a set of operations (for an object).”

Every object is given a type when it is defined. A program — or a part of a program — is type-safe when objects are used only according to the rules for their type.

Unfortunately, there are ways of doing operations that are not type-safe. For example, using a variable before it has been initialised is not considered type-safe.

Complete type safety is the ideal and therefore the general rule for the language. Unfortunately, a C++ compiler cannot guarantee complete type safety, but we can avoid type safety violations through a combination of good coding practice and run-time checks

When we decide to do things that are (type) unsafe, we must do some checking ourselves

Type conversions can be —

  • Safe — we can say conversion are safe when no information is lost that is, we can copy the resulting back and get the original value
  • Unsafe — “hat a value can be turned into a value of another type that does not equal the original value.

Unsafe conversions are also called “narrowing” conversions, because they put a value into an object that may be too small (“narrow”) to hold it.

eg

double to int
double to char
double to bool
int to char
int to bool
char to bool

Use {} initialisers to avoid accidents, and when you want a conversion, check the value before assigning

C++11 introduced an initialisation notation that outlaws narrowing conversions

we could (and should) rewrite the troublesome examples above using a {}-list notation, rather than the = notation

The {}-list-based notation is known as universal and uniform initialisation

eg

using this we will encounter warning of narrowing conversions

Any further suggestions will be highly appreciated.

Thank you,

reference — Principles and Practice Using C++ (2nd Edition)
Bjarne Stroustrup

--

--