SFML community forums

Help => General => Topic started by: Stauricus on August 30, 2020, 05:15:31 pm

Title: drawing derived classes
Post by: Stauricus on August 30, 2020, 05:15:31 pm
hi
i believe this is a newbie issue related to SFML structure and C++
if I have a class derived from two drawables, like this:
class Board : public sf::Text, public sf::Sprite{
    ///etc;
};

how can I draw this class using a sf::RenderWindow? if I try, for example
window.draw(board.Sprite);
I get an error saying
 invalid use of ‘sf::Sprite::Sprite’
but how do I make the window draw the sprite and then the text? is it mandatory that i override the draw function in Board class, pass a window reference, and then draw each one of the drawables from inside the class?
thanks!
Title: Re: drawing derived classes
Post by: Laurent on August 30, 2020, 06:06:43 pm
A class cannot be both a sprite and a text. Most likely, it contains both.
Title: Re: drawing derived classes
Post by: pbortler on August 31, 2020, 03:09:50 pm
You generally don't want to derive from any objects in SFML except interfaces like Drawable or Transformable. Your Board shouldn't be a Text or a Sprite object, but instead it should manage Text and Sprite objects and the Board itself will at most be a sf::Drawable. So you want those Text and Sprite objects to be members, and you probably want a draw() function that handles drawing them (encapsulation is good!).

Derive Board from sf::Drawable, then implement a draw() function that draws the text, then the sprite.

Something like:

void Board::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
    target.draw(text, states);
    target.draw(sprite, states);
}

Then you can just pass the Board instance to the draw() on the window like:

sf::Window window(...);
Board board;
window.draw(board);
Title: Re: drawing derived classes
Post by: Stauricus on September 01, 2020, 01:58:21 am
my idea was to make derived classes that could handle easily texts, sprites, and some more atributes and methods. i'll just put text and sprite as public access members, then.
(but it is kinda ugly)  :-X

thanks!