简体   繁体   中英

C++: Which gets called/initialized first? The Class constructor or constructor(s) of its member variable(s)?

How does something like this get initialized in Cpp, when in my main , I do: Testing test ?

class Testing
{
public:
    Testing();
    void initalize();
    ~Testing();

    void run();

private:
    int x;
    int y;
    int z;

    bool isBugged;

    OtherClass otherClass_;
};

What is the order?

The class constructor gets called first and an initializer list may be used to parameterize member constructor calls, otherwise their default constructors are used at the point of class constructor entry.

Class() : otherClass_("fred", 42) {
//ctor body
}

would invoke OtherClass 's ( OtherClass(char *name, int age) , say) constructor before the Class 's ctor body. Otherwise the default constructor (parameterless) would be used. But as the members are available in the body they are constructed before the body is entered. The example above is an initializer list and is the opportunity for Class 's constructor to explicitly invoke member constructors which would otherwise resolve to default constructor calls at that point.

The order of member construction is the order in which they appear (of declaration) in the class declaration. Your compiler should warn you if this differs to the order you appear to be calling constructors in the initializer list.

You don't show the code for the constructor, but assuming its trivial then the only thing that gets constructed within Testing() is OtherClass .

The other member variables won't be initialized if test is of automatic storage , or will be statically intialized if of static storage . That means that if test is of automatic storage , their members x et.al. will have an indeterminate value, just as when they are declared as function variables.

First the base class sub-objects are initialised, in the order they're declared (although your class doesn't have any of these).

Then the members are initialised, in the order they're declared. If they appear in the constructor's initialiser list, then they're initialised as specified there; otherwise they are default-initialised. In the case of your int and bool members, and POD types in general, this means they are left uninitialised (or zero-initialised if the object has static storage duration), unless they are in the initialiser list.

Finally, the constructor body is executed. If that returns normally, then the object is fully constructed.

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