Luv
Luv

Reputation: 5451

When does the storage allocation takes place in C++?

class A
{
public:
A() {}
};

A b;     //global variable

void fun(void)
{
A a;
}

int main()
{
fun();
}

In this code, I have 2 questions (UPDATED)

  1. When does the storage for object a allocated, when the fun() is called in main() i.e. at runtime or at the compile time?

  2. For global variable b, when storage will be allocated for it and when its constructor will be called?

Upvotes: 0

Views: 89

Answers (1)

John Dibling
John Dibling

Reputation: 101456

a is a local variable allocated in the body of fun(). An A is instantiated every time you call fun(), and then it is de-instantiated (destroyed, destructor called) when the object falls out of scope -- which in this case is when fun() returns.

A's constructor is called when the object is instantiated.

None of this happens at compile-time.

Upvotes: 3

Related Questions