Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversions in C++

Given the following code, why doesn't the compiler resolve the implicit conversion when constructing Bar? That is, construct Foo just like a was constructed which is (should) then be used to construct Bar?

#include <string>

class ImplicitlyConvertToChar
{
public:
  ImplicitlyConvertToChar(const char* a_char)
    : m_string(a_char)
  { }

  ImplicitlyConvertToChar(const char* a_char, size_t a_end)
    : m_string(a_char)
  {
  }

  template <typename T_String>
  ImplicitlyConvertToChar(T_String const& a_string)
    : m_string(a_string.begin())
  {
  }

  operator char const * () const
  { return m_string; }

  const char* m_string;
};

class Foo
{
public:

  Foo(const ImplicitlyConvertToChar& a_charLike)
    : m_string(a_charLike)
  { }

  const char* m_string;
};

class Bar
{
public:
  Bar(const Foo& a_foo)
    : m_foo(a_foo)
  { }

  Foo m_foo;
};

int main()
{
  Foo a("this works");
  Bar b("Why doesn't this?");
}
like image 666
Samaursa Avatar asked Aug 12 '13 15:08

Samaursa


1 Answers

You are not allowed more than one user defined implicit conversion. The Foo example involves one, the Bar example involves two.

like image 159
juanchopanza Avatar answered Sep 22 '22 00:09

juanchopanza