Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

Implicit conversion
Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions.

Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

Explicit conversion
C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors.

#include <iostream>
using namespace std;

class A {

public:
    A()
    {
        age
=30;
    }
   
int age;
};
class B {
public:
   
int Age;
    B (A a) {Age
=a.age*100;
    }
};

void CastingSample()
{
   
//implicit converstion for fundamental data type
    short a=2000;
   
int b;
    b
=a;
   
// impliclit converstion for object, which affect classes that include specific constructors or operator functions to perform conversions
    A aa;
    B bb
=aa;
    cout
<<bb.Age<<endl; // Output: 3000

   
//explicit conversion
    {
       
short a=2000;
       
int b;
        b
= (int) a;    // c-like cast notation
        b = int (a);    // functional notation
    }

}

相关文章: