When does C ++ call a constructor on an object that is a member of a class?

let's say i have a class

class MyClass { public: AnotherClass myObject; }; 

My problem is that I want to initialize myObject with arguments to the constructor, exactly if I would declare it on the stack during the function

 AnotherClass myObject(1, 2, 3); 

but I want to do this for a class member in the constructor:

 MyClass::MyClass() { myObject = ...? ... } 

The problem is what exactly. If I declare a member of a class that has a constructor, will C ++ call the default constructor? How can I declare a variable in a class definition, but initialize it in the constructor?

Thanks for any answers!

+4
source share
7 answers

Use ctor-initializer. Members are initialized after the base classes and before the constructor body is executed.

 MyClass::MyClass() : myObject(1,2,3) { ... } 
+8
source

You can use the list of initializers.

 class MyClass { public: MyClass() : myObject(1,2,3){ } AnotherClass myObject; }; 
+8
source
+4
source
 class A { public: A(int); }; class B { public: B(); private: A my_a_; }; // initialize my_a by passing zero to its constructor B::B() : my_a_(0) { } 
+3
source

always use a list of initializers:

 MyClass::MyClass() : myObject( 1, 2, 3 ) { //myObject = don't do this, bad practice! } 

see http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

+3
source

The best way I can think of is to initialize a member in the ctor class, for example:

 class MyClass { public: MyClass(int param) : m_Object(param) { }; private: OtherClass m_Object; }; 

Then you can explicitly initialize the element using any ctor that you want (and also provide several commands with different parameters for both classes).

+1
source

Or specify suitable constructors:

 struct Foo{ Foo(const Bar& b): myBar(b){} Bar myBar; } //... Foo myFoo1( Bar(1,2,3) ); Foo myFoo2( Bar(3,2,1) ); 

Or, if you do not want to show the panel, you can set parameters, for example

 struct Square{ Square(const int height, const int width): myDimension(width,height){} Dimension myDimension; } //... Square sq(1,2); Square sq(4,3); 
0
source

All Articles