c++ - Initializing private member variables of a class -


i apologize in advance because of verbiage may not 100% correct.

i have class this:

class classname { private:     anotherclass class2; public:   classname();   ~classname(); ... 

in constructor of class, among other things, put line

classname::classname() {     anotherclass class2;  } 

which how thought supposed initialize objects in c++, noticing (through gdb) 2 anotherclass objects being created. once on constructor definition again on initialization line. reasoning behind this? if wanted use more complicated constructor anotherclass(int a, int b), create temporary object create correct 1 shortly after?

anotherclass class2; creates local object inside constructor body, gets destroyed @ end of body. not how class members initialized.

all class members initialized before entering constructor body, is, in member initializer list between constructor signature , body, starting : , separated ,s, so:

classname::classname() :     class2(argumentstopasstoclass2constructor),     anothermember(42) // example {     /* constructor body, empty */ } 

if don't want pass arguments class2 constructor don't have put in initializer list. default constructor called.

if want call default constructor on of class members, can (and should) omit constructor altogether. implicitly generated default constructor wanted.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -