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?
A copy constructor is a member function of a class that initializes an object with an existing object of the same class. In other words, it creates an exact copy of an already existing object and stores it in a new object.
No, in C++ you cannot call a constructor from a constructor.
The copy constructor and assignment operator just do different things where references are concerned. The copy constructor initializes the reference to point to the same object that the reference points to in the instance that is being copied; the assignment operator actually copies the value of the referenced object.
1 Answer. A constructor cannot specify any return type, not even void. A constructor cannot be final, static or abstract.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With