Implicit conversions with classes

In the world of classes, implicit conversions can be controlled by means of three member functions:

  • Single-argument constructors:allow implicit conversion from a particular type to initialize an object.
  • Assignment operator:allow implicit conversion from a particular type on assignments.
  • Type-cast operator:allow implicit conversion to a particular type.
  1. // implicit conversion of classes:
  2. #include <iostream>
  3. using namespace std;
  4. class A {};
  5. class B {
  6. public:
  7. // conversion from A (constructor):
  8. B (const A& x) {}
  9. // conversion from A (assignment):
  10. B& operator= (const A& x) {return *this;}
  11. // conversion to A (type-cast operator)
  12. operator A() {return A();}
  13. };
  14. int main ()
  15. {
  16. A foo;
  17. B bar = foo; // calls constructor
  18. bar = foo; // calls assignment
  19. foo = bar; // calls type-cast operator
  20. return 0;
  21. }

Type casting

In order to control these types of conversions between classes, we have four specific casting operators:dynamic_cast,reinterpret_cast,static_castandconst_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

  1. dynamic_cast <new_type> (expression)
  2. reinterpret_cast <new_type> (expression)
  3. static_cast <new_type> (expression)
  4. const_cast <new_type> (expression)

const_cast

Can be used to remove or add const to a variable. This can be useful if it is necessary to add/remove constness from a variable.

static_cast

This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc.

dynamic_cast

This cast is used for handling polymorphism. You only need to use it when you’re casting to a derived class. This is exclusively to be used in inheritence when you cast from base class to derived class.

reinterpret_cast

This is the trickiest to use. It is used for reinterpreting bit patterns and is extremely low level. It’s used primarily for things like turning a raw data bit stream into actual data or storing data in the low bits of an aligned pointer.

Reference

  1. Type Conversions