Page 1 of 1

A question about classes (C++) [SOLVED]

Posted: Tue Jan 11, 2011 9:19 am
by superLED
Hello there!
I am currently programming a game engine, but I've come across some problems.

I have a main class (Game), that should take care of most of my stuff.
I also have another class (Player), that holds the values of the player and such.

But I have no idea how to use the Player class inside my Game class, so I can do like this:

Code: Select all

void Game::draw()
{
player.draw(player.x, player.y);
}
Can someone please help me with this?
I want the Game class to be able to handle most of the Player class' functions.

Re: A question about classes (C++)

Posted: Tue Jan 11, 2011 9:56 am
by dandymcgee
Game.h

Code: Select all

#include "Player.h"

class Game {
	private:
		Player player1;
	public:
		Game();
		Update();
		Draw();
}
Game.cpp

Code: Select all

Game::Game() {
	player1.SetPosition(32, 128);
	player1.SetSprite("images/player1.png");
}

void Game::Update() {
	player1.Update();
}

void Game::Draw() {
	player1.Draw();
}
This is one common way to go about it. Simply declare a Player as a member variable as the Game class.

Re: A question about classes (C++)

Posted: Tue Jan 11, 2011 9:57 am
by lotios611
Have your Game class hold a Player object, and have a setPlayer() method in the Game class.

Game class

Code: Select all

class Game
{
public:
//Whatever code
setPlayer(Player player);
private:
Player _player;
}
So now all you have to do is create a player object in your main.cpp or wherever, and than call the setPlayer() method.

Edit: Combine what I said with what dandymcgee said.

Re: A question about classes (C++)

Posted: Tue Jan 11, 2011 10:14 am
by superLED
dandymcgee wrote:Game.h

Code: Select all

#include "Player.h"

class Game {
	private:
		Player player1;
	public:
		Game();
		Update();
		Draw();
}
Game.cpp

Code: Select all

Game::Game() {
	player1.SetPosition(32, 128);
	player1.SetSprite("images/player1.png");
}

void Game::Update() {
	player1.Update();
}

void Game::Draw() {
	player1.Draw();
}
This is one common way to go about it. Simply declare a Player as a member variable as the Game class.
Oh my, exactly what I tried, but I didn't include the player.h in game.h.

Thank you so much! *Hands you a cake*

Re: A question about classes (C++)

Posted: Tue Jan 11, 2011 10:22 am
by dandymcgee
superLED wrote: Oh my, exactly what I tried, but I didn't include the player.h in game.h.

Thank you so much! *Hans you a cake*
It was an honest mistake. ;)

Re: A question about classes (C++)

Posted: Tue Jan 11, 2011 10:47 am
by N64vSNES
dandymcgee wrote:
superLED wrote: Oh my, exactly what I tried, but I didn't include the player.h in game.h.

Thank you so much! *Hans you a cake*
It was an honest mistake. ;)
OMFG! You got cake, NOW I'm jealous :'(