mardi 19 février 2019

What is the preferable way of initializing default arguments of a constructor?

I have seen following two ways of default initializing the arguments in constructors(which is also applicable in normal free functions too).

#include <string>
using UserDefinedType = std::string;

class MyClass
{
    UserDefinedType m_member;
public:
    // Way - 1
    MyClass(const UserDefinedType &obj = UserDefinedType()) : m_member{ obj } {}
    // Way - 2
    //MyClass(const UserDefinedType &obj = {}) : m_member{ obj }  {}
};

  • I know the first will defensively(explicitly) call the constructor of user defined type. What happens in the second way?
  • Which is the preferable way of practicing with modern compilers(C++11 or later) ?

Aucun commentaire:

Enregistrer un commentaire