Reading Access Violations from an Array of Derived Classes

(Corresponds to this question .)

I have a base class Baseand two derived classes Der1and Der2. (See the related question for a basic implementation. Each also has a number of public properties.) In my program, I create an array Baseas follows:

Base *array[10];
int count = 0; // program-wide count of how many objects are in the array

Then later I populate it with instances Der1and Der2as follows:

Der1 d = Der1();
d.x = 0; // Filling in public properties
d.y = 1;
d.z = 3;
array[count] = &d;
count++;

Next to the identical code is used Der2.

Much later, I use an array to call functions defined in these classes:

int result = array[i]->SomeFunction(x, y);

My code compiles fine, but when I try to run it, I get "Unhandled exception in 0x00232d60 in file program.exe: 0xC000005: location of the violation of access 0x04064560".

, , 0,0000 , . double -type, , ( "1.572398880752e-311 # DEN" "-9.2559631349317831e + 061" ).

.NET , , , , ... , ?

+3
4
Der1 d = Der1();

Der1 . d SomeFunction, . Der1 , .

Der1* d = new Der1();

d, :

delete d;
+4

. , . , , , . , .

+6

:

Der1 d = Der1();
...
array[count] = &d;

d , . , - :

array[i]->SomeFunction(x, y);

Since the object previously referencing the pointer at this position is now gone.

+2
source
int result = array[i]->SomeFunction(x, y);

Make sure it is iless than 10 and greater than or equal to 0.

+1
source

Source: https://habr.com/ru/post/1793269/


All Articles