Anyone can explain this weird bit in this line of code to me?
ClassA::ClassA(std::string aName) : name(aName)
Appearantly, this is the declaration of that class
class ClassA
{
public:
std::string name;
ClassA(std::string aName);
};
And the weird line of code appeared in its cpp file
ClassA::ClassA(std::string aName) : name(aName)
It's not polymorphism right? But then, what is it?
This is a constructor with an initialization list:
ClassA::ClassA(std::string aName)
: name(aName) // constructor initialization list
{
// ctor body. name is already initialized here
}
It means data member name gets initialized with the value of aName.
It is orthogonal to polymorphism.
it's a member initializer. Member
std::string name;
will be initilized with aName
Using this allows to skip the default constructor of std::string, which would be used otherwise, so this removes some overhead. Another option would be
ClassA::ClassA(std::string aName)
{
// name is fist constucted with default constructor
name = aName; // value is assigned with operator =
}
and this is generally slower, and should be avoided
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