November 1999
Intermediate to advanced
240 pages
5h 22m
English
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 ...
Read now
Unlock full access