Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
ollo Avatar asked Oct 08 '22 12:10

ollo


1 Answers

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.

like image 142
John Avatar answered Oct 13 '22 10:10

John