Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird polymorphism c++? [duplicate]

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?

like image 282
user2345939 Avatar asked Jun 01 '26 06:06

user2345939


2 Answers

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.

like image 51
juanchopanza Avatar answered Jun 03 '26 21:06

juanchopanza


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

like image 22
spiritwolfform Avatar answered Jun 03 '26 20:06

spiritwolfform