c++ - Change type of mainclass object during runtime to subclass -
first of i'm sorry title, couldnt come short describe problem.
what have "text-based adventure game". have main class that's called game, have game loop etc, have class called screen, , childclass screen called screen_one, , screen_two , on, many different "screens" want in game.
so have inside screen, sf::texture , sf::sprite. screen_one , 2 both initialize in respective constructors different values (in case background texture).
and here comes problem, game class has object of type screen, want change depending on in game am, want initialize screen screen_one object in game constructor, , when progress in game screen_two want change screen object screen_two object , therefore right background screen i'm on.
what have (which doesn't work this)
screen_one's constructor
screen_one::screen_one(void) { texture.loadfromfile("filename.png"); // background screen_one sprite.settexture(texture); } inside game class:
game::game(void) : mwindow(sf::videomode(640, 480), "game") // game constructor { sc = screen_one(); // sc declared "screen sc" in game.h } void game::render() // function runs inside game loop { //draw stuff mwindow.draw(this->sc.sprite); } this code runs, gives me white background (so draws nothing). way of doing doesnt work hope can understand im trying , maybe fix or give me way of achieving same thing.
edit: tl;dr can have object of type screen, , during runtime assign screen object screen_one or screen_two in order example change background.
in code
sc = screen_one(); what happening screen part of screen_one being copied sc, not whole object, sc doesn't have enough space it. assuming haven't overridden = operator.
to fix problem, sc should pointer screen. declaration be
screen *sc; then in game constructor, initialize pointer new object of type screen_one:
sc = new screen_one(); when want change screens, delete old screen , make sc point new instance of screen_two:
delete sc; sc = new screen_two();
Comments
Post a Comment