I'm trying to iterate over an array of structs, that are children of an abstract class, by incrementing the pointer to that struct. This works until I add members to that struct, which then results in a memory access violation when trying to derefence the pointer. Here's the code:
struct A {
virtual float Get() = 0;
};
struct B : A {
//int val;
B() {
// val = 0.f;
}
void Set(int v) {
//val = v;
}
float Get() override{
return 0.f; // val;
}
};
struct C : A {
A* previous;
int numPrev;
C() :
previous(nullptr),
numPrev(0)
{}
float Get() override {
float v = 0.f;
A* p = previous;
for (int i = 0; i < numPrev; i++) {
v += p->Get();
p++;
}
return v;
}
void Register(A* prev, int count) {
previous = prev;
numPrev = count;
}
};
C* c;
B* b;
int main()
{
int count = 3;
b = new B[count]();
c = new C[count]();
B* curB = b;
for (int i = 0; i < count; i++) {
curB->Set(i);
curB++;
}
C* cur = c;
for (int i = 0; i < count; i++) {
cur->Register(b, count);
cur++;
}
float res = 0.f;
cur = c;
for (int i = 0; i < count; i++) {
res += c->Get();
cur++;
}
std::cout << res;
delete[] b;
delete[] c;
}
The code above compiles and works fine (as far as I can tell) but if I uncomment all the "val"-stuff in struct B it suddenly throws the mentioned memory access violation. I suspected that the cause might be that "p++" in the Get() method of struct C is incrementing by the wrong amount, because p is a pointer to A but we actually deal with Bs (which are children of A). Adding the member "val" to B would then cause sizeof(B) != sizeof(A) and therefore p++ might not actually jump to the next element but rather "into" the current one causing the violation? Unfortunately changing "p++" to either "p += sizeof(A)" or "p += sizeof(B)" does not solve this, so I'm starting to suspect it's something else...
Does anyone have an idea what could cause this? Am I just blind to a dumb mistake or is there anything else going on?
Thanks a lot in advance!