Re: conversion ctors question
On Jul 19, 4:42 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
"Grey Alien" <g...@andromeda.com> wrote in message
news:ZvOdncEo2pMy7wLbnZ2dnUVZ8qijnZ2d@bt.com...
I am baffled by this behaviour.
I have a class A declared as follows:
class A
{
public: A();
explicit A(const std::string& value);
explicit A(const TimestampParam& value) ;
explicit A(const long value) ;
explicit A(const double value) ;
explicit A(const bool value) ;
A(const Object& value) ;
A(const A);
A& operator= (const A&);
~A();
}
I am using the class in statements like this:
std::vector<A> params ;
[...]
//field descr
field = A("likes donuts"); //calls A::A(const bool)
params.push_back(field);
Why is the compiler casting a std::string to bool?
"likes donuts" is not a std::string. It is a char array
constant, a char pointer if you will. You have no
constructore that takes a char* as a parameter. It seems the
compiler finds bool as the one to use. If you want a char* to
be used as a constructor, then make one.
You mean a char const* constructor, don't you?
The compiler is required to follow the rules of the language.
The language says that there is an implicit conversion of char
const* to bool, that the conversion of char const* to
std::string is a user defined conversion, and that implicit
conversions are to be prefered over user defined conversions.
My understanding is that the intent was that compilers would
warn about such implicit conversions; that they were present
simply to avoid breaking existing code. I don't know of any
compiler which does, however.
In the meantime, it's worth repeating a simple rule concerning
overloading: anytime you overload a function, make sure that
there is an overload for the type a constant value will
typically have. If you overload for any numeric type, for
example, ensure that you also overload for int. (Note that
A(42) will be ambiguous with the original code.) If you
overload for any floating point type, ensure that you also
overload for double. (If you only overload for int and float,
A(1.3) would be ambiguous.) And if you overload for std::string
(or any other class which would typically convert automatically
from a string literal), ensure that you also overload for char
const*. Note too in this respect that bool is an integral (and
thus a numeric) type.
If you're coding guidelines doesn't have a rule along these
lines, add it now.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34