Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 986
cemulate Avatar asked Jul 12 '11 18:07

cemulate


1 Answers

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

MyClass::MyClass() : myObject(1,2,3) {
    ...
}
like image 196
Ben Voigt Avatar answered Nov 15 '22 06:11

Ben Voigt