How to properly inherit base class in c++ and override virtual function

Viewed 84

I'm quite new to c++ and I started looking at the SDL2 library to make a simple platformer game. I'm running into a problem with class inheritance. I have a parent class (GameObj) and a child class (Player). When I try to inherit the the GameObj from Player the compiler tells me the base class is undefined. I am trying to override the update function in the Player class, however since I get a "Base class undefined" error it also tells me that the overrode function did not override anything.

GameObj.h

#pragma once
#include "Game.h"

class GameObj
{
public:
  GameObj(const char* path);

  ~GameObj();

  virtual void update() = 0;

  void render();

protected:
  SDL_Texture* tex{ nullptr };
  SDL_Rect srcR;
  SDL_Rect dstR;
};

GameObj.cpp

#include "GameObj.h"

GameObj::GameObj(const char* path)
{
  tex = TextureManager::LoadImage(path);

  srcR.x = srcR.y = 0;
  srcR.w = srcR.h = 32 * 2;

  dstR.x = dstR.y = 0;
  dstR.w = dstR.h = srcR.w;
}

GameObj::~GameObj() {}

void GameObj::render() {
  TextureManager::DrawTexture(tex, srcR, dstR);
}

Player.h

#pragma once
#include "Game.h"
#include "GameObj.h"

class Player : public GameObj
{
public:
  Player(const char* path, int x, int y);

  ~Player();

  void update() override;

private:
  int x{ 0 };
  int y{ 0 };
  int speed{ 0 };
  int velocity{ 0 };
};

Player.cpp

#include "Player.h"

Player::Player(const char* path, int x, int y) : GameObj(path){};

Player::~Player() {};

void Player::update () 
{
  x++;

  dstR.x = x;
  dstR.y = y;
}

1 Answers

As Retired Ninja commented there is a circular include issue in the code. GameObj.h included Game.h and Game.h included Player.h. To fix this issue I removed the Game.h include in GameObj.h.

GameObj.h

#pragma once
#include <SDL.h>

class GameObj
{
public:
  GameObj(const char* path);

  virtual ~GameObj() = default;

  virtual void update() = 0;

  void render();

protected:
  SDL_Texture* tex{ nullptr };
  SDL_Rect srcR;
  SDL_Rect dstR;
};

GameObj.cpp

#include "GameObj.h"
#include "TextureManager.h"

GameObj::GameObj(const char* path)
{
  tex = TextureManager::LoadImage(path);

  srcR.x = srcR.y = 0;
  srcR.w = srcR.h = 32 * 2;

  dstR.x = dstR.y = 0;
  dstR.w = dstR.h = srcR.w;
}

GameObj::~GameObj() {}

void GameObj::render() {
  TextureManager::DrawTexture(tex, srcR, dstR);
}
Related