Chapter 39. Automatic Conversions

Difficulty: 4

Automatic conversions from one type to another can be extremely convenient. This Item covers a typical example to illustrate why they're also extremely dangerous.

The standard C++ string has no implicit conversion to a const char*. Should it?

It is often useful to be able to access a string as a C-style const char*. Indeed, string has a member function c_str() to allow just that, by giving access to a const char*. Here's the difference in client code:

string s1("hello"), s2("world"); 
strcmp( s1, s2 );                // 1 (error) 
strcmp( s1.c_str(), s2.c_str() ) // 2 (ok)

It would certainly be nice to do #1, but #1 is an error because strcmp requires two pointers and there's no automatic conversion from string to ...

Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.