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...
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
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
// .......
}