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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With