0

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?

Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18

1 Answers1

2

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, e.g., your this->i++;, results in undefined behavior.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Then, It means that memory for both a_ and b_ is allocated prior to constructor of any of them is invoked, right? – Pravar Jawalekar Dec 01 '15 at 03:59
  • 1
    @pravar Yes. When construction of an object starts, memory for the entire object is allocated (of course, that doesn't include any memory dynamically allocated by any of the constructors). – Dietmar Kühl Dec 01 '15 at 04:02