Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are member data constructors called?

I have a global member data object, defined in a header (for class MyMainObj) like this.

class MyMainObj
{
    MyDataObj obj;
}

MyDataObj has a default constructor. When is the constructor for MyDataObj called? Is it called as part of the creation of MyMainObj?


2 Answers

MyDataObj in this case is not a member of MyMainObj, it's a local variable.

But, constructors for data members are called in your class's constructor. The default constructor for every member is called before execution reaches the first line in the constructor, unless you explicitly specify a constructor using an initializer list, in which case that constructor is called instead.

like image 88
2 revsrlbond Avatar answered Mar 15 '26 03:03

2 revsrlbond


With that code, obj isn't a member of MyMainObj -- it's simply a local object inside that constructor. As such, it'll only be constructed when/if that constructor is invoked.

like image 30
Jerry Coffin Avatar answered Mar 15 '26 01:03

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!