-
Type Conversions in C++
We can convert one type to another. There are two types of type conversion:
-
Implicit type conversion
It is done by compiler on its own, without any user input.class Entity{ private: std::string m_name; int m_age; public: Entity(const char* name) : m_name(name), m_age(-1) {} Entity(int age) : m_name("Unknown"), m_age(age) {} }; Entity a = "Lalala"; // we can do it because of implicit convertion Entity b = 22; // we can do it because of implicit convertion
You can disable implicit convertion using
explicit
keyword in front of the constructorclass Entity{ private: std::string m_name; int m_age; public: explicit Entity(const char* name) : m_name(name), m_age(-1) {} explicit Entity(int age) : m_name("Unknown"), m_age(age) {} }; Entity a = "Lalala"; // we can't do it because of explicit keyword Entity b = 22; // we can't do it because of explicit keyword
-
Casting There are 2 ways of casting:
- C style casting
You use
()
and type inside to tell to what type it will cast.int a = 4; double b = (double) a;
- C++ style casting
There are four different ways to cast c++ style:
static cast
It performs compile-time type conversion and is mainly used for explicit conversions that are considered safe by the compiler.int a = 5; double b = static_cast<double>(a);
const cast
The const_cast operator is used to modify the const or volatile qualifier of pointers or references. For example you can cast const int* to a int*.int value = 5; const int* ptr = &value; *ptr = 2; // thats an error because of 'const' int* ptr2 = const_cast<int*>(ptr1); // making ptr2 ptr1 but not const *ptr2 = 2; // that is not error because we deleted const from this pointer
reinterpret cast
The reinterpret cast changes a pointer to any other type of pointer. It doesn't perform any check whether the pointer converted is of the same type or not.struct A{ void printA() { std::cout << "A \n"; } }; struct B{ void printB() { std::cout << "B \n"; } }; A* aPtr = new A(); B* bPtr = reinterpret_cast<B*>(aPtr); bPtr -> printB();
dynamic cast
The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null.
- C style casting
You use
-