C++: Access violation writing location

Your problem is here:

ElemAlg *ea;
ea->GetQuiz(1);

You’re not creating an instance of ElemAlg, so you’re calling a member function on an uninitialized pointer.

Because the member function you are calling isn’t virtual the compiler won’t have to do any runtime lookup, which is why the call goes to GetQuiz. However, the this pointer will be garbage (as ea is uninitialized), so the moment you access a member variable (such as difficultyLevel) you’ll have undefined behaviour. In your case the undefined behaviour leads to an access violation.

Either initialize ea:

ElemAlg *ea=new ElemAlg;
ea->GetQuiz(1)

or, if you don’t need to allocate it on the heap just do:

ElemAlg ea;
ea.GetQuiz(1)

Leave a Comment