Doubt in using pointer to Array of Classes

Say I create a class A.
Then I create an Array of 5 objects of type *A

This is the format of my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class A
{
private:
     int X;
     char Y;
public:
     A();
     void Set(int a = 0, char b = ' ');
};

A::A()
{
     X = 0;
     Y = ' ';
}

void A::Set(int a, char b)
{
     X = a;
     Y = b;
}

int main ()
{
     //......
     A* Object[5];

     for (int i = 0; i < 5; i++)
     {
          Object[i]->Set(i,char(i+65));
     }
     //......
}


Now there is a run time error which states:
Access violation reading location 0xC0000005


When I tried to look at the Values using the Debugger, I found this:
Error: Expression can not be evaluated


Am I doing something wrong?

I can't understand why should this error appear at all...
A* Object[5];

This is an array of five pointers to A. You have not made any objects of type A; you have made pointers to them. Those pointers currently point to some random chunk of memory, so when you try to access that memory, you are trying to read some memory that is not yours and that error appears.

Making a pointer to some object does not make that object as well; just the pointer. You must make the pointer, and also make the object, and then make sure that the pointer points to the object.

For example:

1
2
3
4
5
6
7
8
9
A* pointerToObject; // made a pointer, currently points at some random memory
A   anActualObject; // made an object of type A
pointerToObject = &anActualObject; // now the pointer points to the object
A* pointerToObject = new(A); // Make an object of type A, and pointerToObject is a pointer to that object

A Object[5]; // Made an array of five actual objects, and Object is a pointer to the first one
                  //  i.e. Object[0] will give me an actual object, not a pointer
A* Object[5]; // Made an array of five pointers to objects, and Object is a pointer to the first one
                  //  i.e. Object[0] will give me a pointer, which I haven't yet pointed at anything 
Last edited on
Can it be done by Dynamic Allocation?

Maybe like this:
 
A** Object = new A*[5];



But I get the error now. Thanks for explaining that.

EDIT:
Tried it out, and even now the same error appears. I guess it should have now disappeared...
Last edited on
Try this, it worked for me:
1
2
3
4
5
6
7
8
9
int main()
{
    //......
    A* Object [ 5 ]; // declare an array of pointers
    for ( int i = 0; i < 5; i++)
          Object[i] = new A; // initialize each pointer with an object of type A
    // .......
}
Last edited on
Thanks for that.
Really Appreciated.
Can it be done by Dynamic Allocation?


It can; why do you insist on having an array of pointers to objects? Why not just an array of the objects?
I was using it for Polymorphism.

I was making an array of pointers to the Base Class.

Thanks again
Topic archived. No new replies allowed.