Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an implicit type conversion from pointers to bool in C++?

Tags:

Consider the class foo with two constructors defined like this:

class foo
{
public:
    foo(const std::string& filename) {std::cout << "ctor 1" << std::endl;}
    foo(const bool some_flag = false) {std::cout << "ctor 2" << std::endl;}
};

Instantiate the class with a string literal, and guess which constructor is called?

foo a ("/path/to/file");

Output:

ctor 2

I don't know about you, but I don't find that the most intuitive behavior in programming history. I bet there is some clever reason for it, though, and I'd like to know what that might be?

like image 488
Oystein Avatar asked Nov 06 '10 01:11

Oystein


People also ask

What is implicit conversion in C?

Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.

What happens in implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

Is implicit type conversion bad?

Everyone knows Implicit Conversion is bad. It can ruin SARGability, defeat index usage, and burn up your CPU like it needs some Valtrex.

What is implicit type conversion in programming?

In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement. Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.


1 Answers

It's very common in C to write this

void f(T* ptr) {
    if (ptr) {
        // ptr is not NULL
    }
}

You should make a const char* constructor.

like image 139
Lou Franco Avatar answered Dec 01 '22 11:12

Lou Franco