Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: sf::Drawable + constructor, white square  (Read 1277 times)

0 Members and 1 Guest are viewing this topic.

thief01

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
sf::Drawable + constructor, white square
« on: June 06, 2019, 12:21:54 am »
Hi guys, i will show you my problem on code
This code will show white square.
#include <SFML\Graphics.hpp>

class Button: public sf::Drawable {
  sf::Texture txt;
  sf::Sprite spr;
  sf::Text t;
  sf::Font f;
  virtual void draw(sf::RenderTarget & t, sf::RenderStates s) const {
    t.draw(spr, s);
  }
  public:
    Button() {
      txt.loadFromFile("txt.png");
      spr.setTexture(txt);
    }
};
class Invet: public sf::Drawable {
  Button b;
  virtual void draw(sf::RenderTarget & t, sf::RenderStates s) const {
    t.draw(b, s);
  }
  public:
    Invet() {
      b = Button();
    }
};

int main() {
  Invet i;
  sf::RenderWindow w(sf::VideoMode(1280, 780), "e");
  while (w.isOpen()) {
    sf::Event e;
    if (w.pollEvent(e)) {}
    w.clear();
    w.draw(i);
    w.display();
  }
  return 0;
}
or this
//Invent
public:
Button b;
//main
Invet i;
i.b=Button()
but if...
Invet() {}
Why i can't use constructor to second class from first, or like object be second object?

SFML 2.5.1

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: sf::Drawable + constructor, white square
« Reply #1 on: June 06, 2019, 07:57:02 am »
Quote
b = Button();
This is a copy, and you don't define correct copy constructor & assignment operator for your Button class: the new spr sprite will still use the txt texture of the previous instance, not the new one.

A common rule is to avoid managing resources (sf::Texture, sf::Font, ...) directly in classes that use them. Or, prevent copy semantics for those classes and manage their instances like true entities.
Laurent Gomila - SFML developer

thief01

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Re: sf::Drawable + constructor, white square
« Reply #2 on: June 06, 2019, 10:41:47 am »
Quote
b = Button();
This is a copy, and you don't define correct copy constructor & assignment operator for your Button class:

Right, with initialization works.

common rule is to avoid managing resources (sf::Texture, sf::Font, ...) directly in classes that use them. Or, prevent copy semantics for those classes and manage their instances like true entities.

Thanks for tip.