How a function call works on a unified data object object in the list of constructor initializers

Consider the program below,

#include <iostream> using namespace std; class A { public: A() { cout << "A constructor\n"; } void f() { cout << "A used\n"; this->i++; } private: int i; }; class B { public: B(A & a1) { cout << "B constructor\n"; a1.f(); } }; class Z { public: Z() : a_(), b_(a_) {} private: B b_; A a_; }; int main() { Z z; return 0; } 

Below is the result,

 B constructor A used A constructor 

My question is

Since data element objects are created in the order of their declaration in the class, it means that b_ will be created first. But how can it call a function on an a_ data element that has not yet been created? Does the compiler do some optimization to translate a call to f() to a regular function call? If so, how does this->i++ ?

0
source share
1 answer

The compiler will not fight you when you explicitly tell it somewhere to pass a link to an uninitialized object. In the end, the function you pass in can be used to actually initialize the object.

However, access to uninitialized data, for example your this->i++; , leads to undefined behavior.

+2
source

All Articles