Pass an object to another object constructor

Let me know if I'm outta line for posting an SFML question in a general C++ forum but I think this problem has more to do with my understanding of the language than the library.

So basically I'm trying to pass a reference of an object(sf::renderwindow) to a class(game_object) and then set that as a public referenced object within the class itself.

That way any of Game_objects members can use 'sf::RenderWindow' members without the reference being explicitly passed to the member itself (thats no problem just seems inefficient).

Heres a snippet of what I'm trying to do.

Class Header

1
2
3
4
5
6
7
8
9
10
11
12
class Game_Object { 
    public: 

        // constructor / destructor 
        Game_Object(sf::RenderWindow &Window); 
        virtual ~Game_Object(); 
  
        //{ SFML stuff 
        sf::RenderWindow Draw_target; 
        sf::Sprite Sprite 

};


.cpp Constructor

1
2
3
Game_Object::Game_Object(sf::RenderWindow &Window){ 
    Draw_target = &Window; 
}



Main

1
2
3
4
int main{ 
   sf::RenderWindow GameWindow; 
   Game::Object Ship(GameWindow); 
}


I've tried making 'draw_target' a pointer and using the '->' operator to access the 'draw' member of the render window. But the compiler didn't like that.

So how is this normally done if at all?
Last edited on
When you attempt to assign a reference to a normal object, you perform a copy.

However, I'd have to say that if you want to make your Game::Objects like that, I'd probably just make them inherit from sf::Drawable (or whatever). Tbh, they shouldn't really have to know anything about GameWindow to work.
When you attempt to assign a reference to a normal object, you perform a copy.

Do you mean here...
1
2
3
Game_Object::Game_Object(sf::RenderWindow &Window){ 
    Draw_target = &Window; 
}

..when I use the reference to 'Window' in both the argument and the 'Draw_target' Declaration?
Or do you mean using a reference period performs a copy. If so than that was not my thinking.

However, I'd have to say that if you want to make your Game::Objects like that, I'd probably just make them inherit from sf::Drawable (or whatever).

Yeah Ive read about inheriting from sf::drawable but heard it was kinda bad practice.

Tbh, they shouldn't really have to know anything about GameWindow to work.

That had crossed my mind. Perhaps drawing should happen in a 'window' or 'game/engine' class with a loop for all 'game_objects'?



Topic archived. No new replies allowed.