R
Russell Reagan
In a newer version of a chess program I am writing, I have created classes
that are (more or less) drop in replacements for things that used to be
plain old integer or enumerated variables (colors, piece types, squares,
etc.). To accomplish this, I used implicit conversions. For instance, a
color used to be:
typedef int Color;
// and a few constants...
Now a color is (paraphrased):
class Color {
private:
int color;
public:
// ...
operator int () { return color; }
// ...
};
The reason for moving to these simple classes (which are just int wrappers)
was so that I could verify the validity of the data. For instance:
operator int () { assert(color == white || color == black); return color; }
However, I've been told by several people that implicit conversions are
"evil". I can see how they could be the source of very nasty bugs for a more
hefty class, but what about for something as simple as these classes which
are nothing more than int wrappers? The way I'm using them, they kind of
_are_ int's, so how could it cause bugs if there is an implicit conversion?
Would it be possible for an instance of Color to be implicitly converted and
not validate its internals any longer? If that is possible, I could foresee
a potentially hard to find bug. That would give a sense of false security,
and I'd probably look for the bug elsewhere, assuming (incorrectly) that my
color was still valid since the assert didn't fail.
that are (more or less) drop in replacements for things that used to be
plain old integer or enumerated variables (colors, piece types, squares,
etc.). To accomplish this, I used implicit conversions. For instance, a
color used to be:
typedef int Color;
// and a few constants...
Now a color is (paraphrased):
class Color {
private:
int color;
public:
// ...
operator int () { return color; }
// ...
};
The reason for moving to these simple classes (which are just int wrappers)
was so that I could verify the validity of the data. For instance:
operator int () { assert(color == white || color == black); return color; }
However, I've been told by several people that implicit conversions are
"evil". I can see how they could be the source of very nasty bugs for a more
hefty class, but what about for something as simple as these classes which
are nothing more than int wrappers? The way I'm using them, they kind of
_are_ int's, so how could it cause bugs if there is an implicit conversion?
Would it be possible for an instance of Color to be implicitly converted and
not validate its internals any longer? If that is possible, I could foresee
a potentially hard to find bug. That would give a sense of false security,
and I'd probably look for the bug elsewhere, assuming (incorrectly) that my
color was still valid since the assert didn't fail.