Louise BC Louise BC - 1 year ago 162
C++ Question

Error: "Allocating an object of abstract class type" despite all virtual functions being implemented

I'm receiving error "Allocating an object of abstract class type 'MainGame" even though all virtual functions have been implemented. Below are the relevant code snippets:


#include "Gamestate_MainGame.h"

int main() {
Game game;
if (game.init(new MainGame))
return 0;


#ifndef Gamestate_h
#define Gamestate_h
#include <SDL2/SDL.h>
#include "Game.h"

class GameState {
virtual bool init(Graphics* graphics, Game* game) = 0;
virtual void quit() = 0;

virtual void handleEvents(SDL_Event* e) = 0;
virtual void logic() = 0;
virtual void render() = 0;

Game* game = NULL;
Graphics* graphics = NULL;


#ifndef Gamestate_MainGame_h
#define Gamestate_MainGame_h
#include <vector>
#include <SDL2_mixer/SDL_mixer.h>
#include "Gamestate.h"
#include "Graphics.h"
#include "Tile.h"

class MainGame : public GameState {
// Gamestate Functions
bool init(Graphics* graphics, Game* game);
void quit();

void handleEvents(SDL_Event& e);
void logic();
void render();

// MainGame functions - make private?
void makeTiles();
void loadPositions(const int & n);
void scrambleTiles(std::vector<Tile> t);
void restart();

bool isSolved();
bool isNeighbor(const Tile& a, const Tile& b);
int getClickedTile(const int& x, const int& y);

Game* game = NULL;
Graphics* graphics = NULL;

int clickedTile { -1 };
int clicks { 0 };
bool gameExit { false };
bool gameWin { true };
bool catMode { true };

std::vector<Tile> tiles;
std::vector<SDL_Rect> positions;

Mix_Chunk* click = NULL;



#ifndef Game_h
#define Game_h
#include <vector>
#include <SDL2/SDL.h>
#include "Graphics.h"

class GameState;

class Game {

bool init(GameState* state);
void loop();

void pushState(GameState* state);
void popState();
void setQuit();
bool quit { false };

Graphics graphics;
SDL_Event event;
std::vector<GameState*> states;

Uint32 new_time;
Uint32 old_time;

//internal loop functions
void update();
void render();

void quitGame(); //will free SDL resources and perform cleanup of states

All MainGame functions are defined in Gamestate_MainGame.cpp. Thank you for your help!

Answer Source
virtual void handleEvents(SDL_Event* e) = 0;

is a different prototype than

void handleEvents(SDL_Event& e);

You should mark all your overridden functions with override then the compiler will do the heavy lifting for you and tell you whether you messed up or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download