16

Is it possible for an overloaded constructor to somehow call another constructor within the class, similar to the code below?

class A {
public:
    A(std::string str) : m_str(str) {}
    A(int i) { *this = std::move(A(std::to_string(i))); }

    std::string m_str;
};

The code above works, yet I am afraid that calling this in the constructor might lead to undefined behavior.

If it does could you please explain why and also suggest a better alternative?

Makaronodentro
  • 907
  • 1
  • 7
  • 21

1 Answers1

29

C++11 introduced delegating constructors:

class A
    {
    public:
    std::string m_str;
    A(std::string str) : m_str(str) {} // target constructor
    A(int i) : A(std::to_string(i)) {} // delegating constructor
    };
acraig5075
  • 10,588
  • 3
  • 31
  • 50