简体   繁体   中英

When will C++ call the constructor on an object that is a class member?

let's say I have a class

class MyClass {
    public:
        AnotherClass myObject;
};

My issue is that I want to initialize myObject with arguments to it's constructor, exactly if I were declaring it on the stack during a function

AnotherClass myObject(1, 2, 3);

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

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

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

Thanks for any answers!

You can use an initializer list.

class MyClass {
    public:
        MyClass() : myObject(1,2,3){ }
        AnotherClass myObject;
};

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

MyClass::MyClass() : myObject(1,2,3) {
    ...
}
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)
{
}

always use the initializer list:

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

The best method I can think of is to initialize the member in the class ctor, like so:

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

private:
    OtherClass m_Object;
};

You can then explicitly initialize the member with whichever ctor you want (as well as providing multiple ctors with different params for both classes).

Or provide proper 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 don't want to expose bar then 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM