c++ - Using Constructor for default member value -


in c++11, can initialize object without using initialization list:

 class z{    int a=0;    int b;    z():b(0){} //<-- initialized    }; 

what i'm wondering class types, of these preferable:

 class z{    std::vector<int>a=std::vector<int>();    //or instead:    std::vector<int>a();    int b;    z():b(0){} //<-- initialized    }; 

there no need explicitly default initialize a, since default constructed. fine:

class z {   std::vector<int> a;   int b = 0;   z() {} //<-- a, b initialized }; 

note second variant function declaration, not initialization:

// function a(), returns std::vector<int> std::vector<int> a(); 

so should have used is

// data member std::vector<int>. default construct it. std::vector<int> a{}; 

of course, if not want default construction, initialization @ point of declaration handy:

std::vector<int> a{0,1,2,3}; 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -