Explicit / Implicit Class Constructors

It’s not just overloading that can be a mess. C++ has a bunch of rules about implicit / explicit type conversion for single argument constructors.

For example:

  1. class MagicNumber {
  2. public:
  3. MagicNumber(int value) {}
  4. };
  5. void magic(const MagicNumber &m) {
  6. //...
  7. }
  8. int main() {
  9. //...
  10. magic(2016);
  11. return 0;
  12. }

The function magic() takes a const MagicNumber & yet we called it with 2016 and it still compiled.
How did it do that? Well our MagicNumber class has a constructor that takes an int so the compiler
implicitly called that constructor and used the MagicNumber it yielded.

If we didn’t want the implicit conversion (e.g. maybe it’s horribly expensive to do this without knowing),
then we’d have to tack an explicit keyword to the constructor to negate the behaviour.

  1. explicit MagicNumber(int value) {}

It demonstrates an instance where the default behavior is probably wrong. The default should be explicit
and if programmers want implicit they should be required to say it.

C++11 adds to the confusion by allowing classes to declare deleted constructors which are anti-constructors
that generate an error instead of code if they match. For example, perhaps we only want implicit int constructors to
match but we want to stop somebody passing in a double. In that case we can make a constructor for double and then
delete it.

  1. class MagicNumber {
  2. public:
  3. MagicNumber(int value) {}
  4. MagicNumber(double value) = delete;
  5. };
  6. void magic(const MagicNumber &m) {
  7. //...
  8. }
  9. //...
  10. magic(2016); // OK
  11. magic(2016.0); // error: use of deleted function 'MagicNumber::MagicNumber(double)'

How Rust helps

Rust does not have constructors and so there is no implicit conversion during construction. And since there is no
implicit conversion there is no reason to have C++11 style function delete operators either.

You must write explicit write “constructor” functions and call them explicitly. If you want to overload the function
you can use Into<> patterns to achieve it.

For example we might write our MagicNumber constructor like this:

  1. struct MagicNumber { /* ... */ }
  2. impl MagicNumber {
  3. fn new<T>(value: T) -> MagicNumber where T: Into<MagicNumber> {
  4. value.into()
  5. }
  6. }

We have said here that the new() function takes as its argument anything that type T which implements the trait Into<MagicNumber>.

So we could implement it for i32:

  1. impl Into<MagicNumber> for i32 {
  2. fn into(self) {
  3. MagicNumber { /* ... */ }
  4. }
  5. }

Now our client code can just call new and providing it provides a type which implements that trait our constructor will work:

  1. let magic = MagicNumber::new(2016);
  2. // But this won't work because f64 doesn't implement the trait
  3. let magic = MagicNumber::new(2016.0);