Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convenience constructor in C++? [duplicate]

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?

like image 676
Makaronodentro Avatar asked Feb 08 '17 13:02

Makaronodentro


People also ask

What is the point of a copy constructor?

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.

Can a constructor call another constructor of the same class C++?

No, in C++ you cannot call a constructor from a constructor.

Does an object created with a copy constructor reference the same memory location that the original object references?

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.

Which constructor declaration is not valid in C++?

1 Answer. A constructor cannot specify any return type, not even void. A constructor cannot be final, static or abstract.


1 Answers

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
    };
like image 145
acraig5075 Avatar answered Oct 08 '22 05:10

acraig5075