简体   繁体   中英

How function call is working on an unitialized data member object in constructor's initilalizer list

Consider below program,

#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 output it produces,

B constructor
A used
A constructor

My Question,

Since data member objects are created in order of their declaration in class, hence b_ will be created first. But how it is able to call a function on data member a_ which is still not created? Does compiler performs some kind of optimization to translate call to f() to a plain function call? If yes, then how this->i++ is working?

The compiler won't fight you when you explicitly instruct it to pass a reference to an uninitialized object somewhere. After all, the function you pass it to may be used to actually initialize the object.

However, accessing uninitialized data, eg, your this->i++; , results in undefined behavior.

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