-2
#include <iostream>
using namespace std;

class A
{
    int x;
public:
    A() { cout << "A's constructor called " << endl;  }
};

class B
{
    static A a;
public:
    B() { cout << "B's constructor called " << endl; }
    static A getA() { return a; }
};

A B::a;  // definition of a

int main()
{
    B b1, b2, b3;
    A a = b1.getA();

    return 0;
}

Output:
A's constructor called
B's constructor called
B's constructor called
B's constructor called

I am not able to understand how we got the above output and how object declared of 1st class in class 2nd.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Ashish
  • 27
  • 1
  • 2
  • 7
  • Why do you think the output is wrong? – drescherjm Feb 25 '16 at 18:49
  • 2
    The `static` declaration of `A` in class `B` causes the first constructor called. The compiler will emit code to initialize global and *static* variables before `main` is called. – Thomas Matthews Feb 25 '16 at 18:49
  • 4
    If you step through your code with the debugger, it should become pretty clear why it's behaving like this. `static A a;` is a static object and will be instantiated once for all instances of `B`. – πάντα ῥεῖ Feb 25 '16 at 18:50
  • Look at the generated assembly code and verify that the compiler emitted code for the assignment statement in `main`. Since the `a` variable is not used in `main`, the compiler may not have generated any code that constructs an instance of `A`. (Or it may have generated the code, then removed the code during optimization.) – Thomas Matthews Feb 25 '16 at 18:51
  • ok got the concept. thanks all. – Ashish Feb 25 '16 at 18:57

1 Answers1

2

I am not able to understand how we got the above output and how object declared of 1st class in class 2nd.

static A a; 

is a static member of class B and will be instantiated once for all instances of B.

This happens even before main() is entered, and you're lucky that

cout << "A's constructor called " << endl;  

worked well, since static instances aren't guaranteed to be initialized in a specific order (note that std::cout is just another static object instance).

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • "`static` instances aren't guaranteed to be initialized in a specific order" -- That's not quite right, see [here](http://stackoverflow.com/questions/1421671/when-are-static-c-class-members-initialized), but I understand the spirit of your statement. "objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions (not declarations)" – James Adkison Feb 25 '16 at 19:22