next up previous
Next: When should I use Up: class and struct Previous: How can I access

How do I prevent the compiler from doing implicit type conversions?

Use the keyword explicit on the constructor. Forcing explicit conversions is usefull to make the programmers aware of the conversion. This is especially interesting for time consuming conversions.
struct A
{
  A() {}
};

struct B
{
  B() {}
  B(const A &a) {}
};

struct C
{
  C() {}
  explicit C(const A &a) {}
};

void	fb(B b) { /* ... */ }

void	fc(C c) { /* ... */ }

void	function()
{
  A	a;
  B	b;
  C	c;

  fb(a);    // ok, conversion is implicit
  fc(a);    // error
  fc(C(a)); // ok, conversion is explicit
}



Alexis Angelidis (PhD) 2005-01-11