Reputation: 1
I have the following code snippet:
A.h
include B.h
class A
{
public:
void createB();
B* getB();
private:
B *b;
};
A.cpp
void A::createB()
{
b = new B();
}
B* A::getB()
{
return b;
}
Main.cpp
int main()
{
int n = 3;
A *a_array = new A[n];
for ( int i = 0; i < n; i++ ) {
A *a = new A();
a_array[i] = *a;
}
for ( int i = 0; i < n; i++ ) {
A a = a_array[i];
a.createB();
}
a_array[0].doStuff(); // OK
a_array[0].getB(); // returns NULL
}
Output:
A created
A created
A created
B created
A destroyed
B created
A destroyed
B created
A destroyed
It seems A objects are destroyed in the loop, but i have access them without loop, but can't access to A's object members.
Upvotes: 0
Views: 920
Reputation: 4497
A a = a_array[i] in the second for loop creates a copy on the stack which is deleted again after the loop scope. The a_array[0] access after the loop refers to another object then.
Upvotes: 0
Reputation: 36082
int main()
{
int n = 3;
A *a_array = new A[n];
for ( int i = 0; i < n; i++ ) {
A *a = new A();
a_array[i] = *a; // here you are copying a and then causing a memleak
}
what you probably meant was
A **a_array = new A*[n];
for ( int i = 0; i < n; i++ ) {
A *a = new A();
a_array[i] = a; // now array points to instance of a
}
now when you reference the pointer:
for ( int i = 0; i < n; i++ ) {
A* a = a_array[i];
a->createB();
}
a_array[0]->doStuff(); // OK
a_array[0]->getB(); // returns NULL
...
don't forget to delete array and instances of a.
You should however take a look at vector<>
and array<>
, using STL containers is better
Upvotes: 0
Reputation: 70939
The problem is that in the second loop you call createB on a copy of the corresponding element in the array a_array
. Try changing the loop to:
for ( int i = 0; i < n; i++ ) {
A& a = a_array[i];
a.createB();
}
Also please note you have a lot of memory leaks in your program - you allocate a lot of stuff that you never free.
In the first cycle there is no need to allocate a dynamically before assigning it to an element in the array. Simply do(as pointed out by Pete Becker):
for ( int i = 0; i < n; i++ ) {
a_array[i] = A();
}
Upvotes: 2