I am very new to C++, and am following along with this tutorial and have come across this class constructor:
class Player: public Entity
{
private:
std::string m_Name;
public:
Player(const std::string& name)
: m_Name(name) {}
std::string GetName() override
{
return m_Name;
}
};
So, from what I understand, when we create an instance of the class, we pass a name into the constructor, and it sets m_Name = name, but why is it defined in a weird way and not inside the {} body of the constructor?
I have tried the alternative below, and it works all the same:
Player(const std::string& name)
{
m_Name = name;
}
I am just wondering what is going on in the first example.
In this constructor
the object
m_Nameis created using the copy constructor of the classstd::string.In this constructor
At first the object
m_Nameis created using the default constructor of the classstd::stringand then within the body of the constructor of the classPlayerthere is used the copy assignment operator of the classstd::stringto assign the value ofnameto the objectm_Name.That is within the body of the constructor of the class
Playerthe data memberm_Nameshall be already created.So in general it is more efficient to create an object using only the copy constructor instead of calling the default constructor and the copy assignment operator..
Another problem with using the second implementation of the constructor is that you can not such a way to create a constant data member of the class or you also can not to initialize a data member that has a referenced type.
Constant objects and references shall be initialized when they are created.
For example if you will declare the following class
then the compiler will issue an error saying that references must be initialized.
But if you will change the constructor like
then the code will be compiled successfully.