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
Player(const std::string& name)
: m_Name(name) {}
the object m_Name
is created using the copy constructor of the class std::string
.
In this constructor
Player(const std::string& name)
{
m_Name = name;
}
At first the object m_Name
is created using the default constructor of the class std::string
and then within the body of the constructor of the class Player
there is used the copy assignment operator of the class std::string
to assign the value of name
to the object m_Name
.
That is within the body of the constructor of the class Player
the data member m_Name
shall 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
class A
{
private:
std::string &m_Name;
public:
A( std::string &name )
{
m_Name = name;
}
};
then the compiler will issue an error saying that references must be initialized.
But if you will change the constructor like
A( std::string &name ) : m_Name( name )
{
}
then the code will be compiled successfully.