I'm exercising with understanding classes better. I have a pseudo layout for a game, including an "Engine" class that has a Draw(x, y, ...) method, and a Player class. I also have a "Game" class that simply inherits from Engine and has the GameLoop() method.
My issue is: inside the Game object GameLoop method I want my Player player;
to draw himself via a method DrawSelf(this);
e.g. player.DrawSelf(this);
, effectively passing the Game object by reference and allowing me to define WITHIN the DrawSelf method, how to Draw(x, y, ...).
Essentially I want to be able to call Draw(x,y) from the Player class.
I also have a minor issue at the moment with "Game does not name a type" error, which I assume is something to do with my header declarations, but I am not exactly sure. Here is what I have so far:
engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include <iostream>
class Engine
{
public:
void Draw(float x, float y);
};
Engine::Draw(float x, float y)
{
std::cout << "Drawing at (" << x << ", " << y << ")." << std::endl;
}
#endif /*ENGINE_H*/
main.h
#ifndef MAIN_H
#define MAIN_H
#include "engine.h"
#include "player.h"
class Game : public Engine
{
public:
void GameLoop(int frames);
};
#endif /* MAIN_H */
main.cpp
#include "main.h'
class Game::GameLoop(int frames)
{
Player player(this); // create player object here and hope to pass Game object to it.
for (int i = 0; i < frames; i++)
{
player.DrawSelf();
}
};
int main()
{
Game myGame;
myGame.GameLoop(5);
return 0;
}
player.h
#ifndef PLAYER_H
#define PLAYER_H
class Player
{
public:
class Game; // forward declare to help compiler
float x, y;
Game* game; // pointer to game object to be initialized to game object passed in constructor
public:
Player(game* oGame);
void DrawSelf();
};
#endif /* PLAYER_H*/
player.cpp
#include "main.h"
Player::Player(Game* oGame)
{
x = 7.0f;
y = -2.0f;
game = oGame; // initializing game object
}
void Player::DrawSelf()
{
game->Draw(x, y); // trying to use Draw method of Game object inherited from Engine
}