Help w/ Passing of Parameters & Constructors

Hey everyone,
I've been using SFML to make the classic space game. Originally I had everything pertaining your own on ship in a 'Player' class but in an attempt to practice OO programming, I've split things up. Now I've run into a problem:

I'll try to simplify the problem as much as possible.

Originally:

Main.cpp
1
2
3
4
5
6
7
8
#include "player.h"
int main () {
   sf::RenderWindow window(sf::VideoMode(800,600,32), "Test");

   Player player(window);
   player.draw_ship();

   return 0; }

Player.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Player {
    public:
        Player(sf::RenderWindow &window);
        void draw_ship();
    Private:
        sf::RenderWindow &Window;
};

Player::Player (sf::RenderWindow &window):
    Window(window)
{}

void Player::draw_ship() {
   window.draw();
}


This solution worked great, had no problems
After splitting up the program, I had "3" files.

Main.cpp
1
2
3
4
5
6
7
8
#include "player.h"
int main () {
   sf::RenderWindow window(sf::VideoMode(800,600,32), "Test");

   Player player; // <------ This is where I'm having problems
   player.ship.draw_ship();

   return 0; }

Player.h
1
2
3
4
5
6
7
#include <ship.h>

class Player {
    public:
       Ship ship;
       "other variables"
};

Ship.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Ship {
    public:
        Ship(sf::RenderWindow &window);
        void draw_ship();
    Private:
        sf::RenderWindow &Window;
};

Ship::Ship (sf::RenderWindow &window):
    Window(window)
{}

void Ship::draw_ship() {
   window.draw();
}


I've been having trouble figuring out how to (I think this is correct) pass the RenderWindow through the Player class into the Ship class. I've experimented around with including constructors in the player class but to no avail.

Any help would be greatly appreciated.
Last edited on
To fix it just repeat the same code you had with class Ship to class Player:

1
2
3
4
5
6
7
8
9
class Player {
    public:
        // pass window to Player's constructor, then pass the window
        // to Ship's constructor (in the initialization list)
        Player(sf::RenderWindow &window) : ship(window) {
        }
};

Player player(window);

1
2
3
4
5
6
class Player {
private:
//variables n stuff
public:
    Player(sf::RenderWindow &window), ship(window) { }
};

Does that fix it?

EDIT: elementary beat me :'(
Last edited on
Thanks guys! It's working now
Last edited on
Topic archived. No new replies allowed.