Yes I know this question has been asked and answered a lot of times and I've tried to understand the previous posts on this (and believe I've tried) but I seriously cannot grasp the concept.
In my program below, the class A array a is created and the default constructor is called four times for each respective element in the array. This part I get. The pointer p is assigned the class object array a. I imagine that p is now pointing to the first element in the array. Now this is where I get lost. The destructor is called 4 times. I've read a lot of explanations but they only seem to confuse me more. I'd really just like a simple explanation of why this is happening.
I'm sorry if this is irritating to ask this again (though I'm sure I won't be the last) but any help from those willing would be greatly appreciated.
My Program plus the output:
#include <iostream.h>
class A
{
public:
A(int i)
{ a=i; }
A()
{
a=0;
cout<<"Default constructor called."<<a<<endl;
}
~A()
{ cout<<"Destructor called."<<a<<endl; }
void Print()
{ cout<<a<<endl; }
private:
int a;
};
void main()
{
A a[4],*p;
int n=1;
p=a;
for(int i=0;i<4;i++)
a[i]=A(++n);
for(i=0;i<4;i++)
(p+i)->Print();
}
Output:
Default constructor called. 0
Default constructor called. 0
Default constructor called. 0
Default constructor called. 0
Destructor called. 2
Destructor called. 3
Destructor called. 4
Destructor called. 5
2
3
4
5
Destructor called. 5
Destructor called. 4
Destructor called. 3
Destructor called. 2