Explicit vs Implicit conversion

Hey guys, my text book is somewhat confusing on this topic.

I know that even if div is of type double, the integer division is done before assignment, so div will be 1 instead of 1.25

If I cast num1 and num2 to doubles, two temporary floating point values are created. Using the cast operator like this is 'explicit conversion'.

What is implicit conversion exactly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 int main()
{
	int num1 = 5;
	int num2 = 4;
	double div = num1 / num2;

	cout << div << endl;

	double div = static_cast<double>(num1) / static_cast<double>(num2);

	cout << div << endl;

	system("pause");
	return 0;
}
> What is implicit conversion exactly?

An implicit conversion is any type conversion that is performed when the expression does not have a cast operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>

int main()
{
    char cstr[20] = "hello" ;

    int i = cstr[0] ; // implicit conversion from char to int

    char* ptr = cstr ; // (implicit) array to pointer conversion
                       // 'array of 20 char' to 'pointer to char'

    const char* cptr = ptr ; // (implicit) qualification conversion
                             // 'pointer to char' to 'pointer to const char'

    // a standard conversion may involve an implicit conversion sequence
    const char* cptr2 = cstr ; // 1. array to pointer conversion
                               // 2. qualification conversion

    // an implicit conversion may combine a standard conversion and a user-defined conversion
    std::string str = cstr ; // standard conversion: 1. array to pointer conversion 2. qualification conversion
                             // user-defined conversion: const char* to std::string (via the converting constructor)

    // an implicit conversion may be contextual
    if(cptr) ; // cptr used in a boolean context; implicit conversion from pointer to bool
}
Topic archived. No new replies allowed.