jeudi 21 juin 2018

Using list initialisation inside a constructor

I have started learning c++ recently. So, here is a quick doubt that I have:

Learning Part I:
While I was reading about list initialization in c++, I got an idea about the difference between direct initialization and copy initialization.

string name = "Deb"; //Copy
string name("Deb"); //Direct

So, I thought - Okay, it's a good thing to stick with direct initialization as the c++ primer suggests copy initialization is somewhat like creating a temp variable.

Learning Part II:
Then when I started learning constructor, the first thing that everyone told me - it helps in initializing the object members.

So, I used the list initialization again. And that throws errors. Why?

class Name{
 string personName;
 Name(){
   personName("Deb");
   }
};

But these alternative approaches work:

personName="Deb";

or

Name():personName("Deb");

Aucun commentaire:

Enregistrer un commentaire