Hi,
I've started to work with SFML and C++ not while ago and drawn some sprites without using objects. However, when I started to use objects, I encountered with "Exception thrown at 0x7994CF80 (sfml-graphics-d-2.dll) in Project_demo.exe: 0xC0000005: Access violation reading location 0x0000020C." error and it crashes my program. What should I do to solve it?
Here's my code:
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
class Coord {
public:
float x;
float y;
Coord() {}
Coord(float x, float y) : x(x), y(y) {}
};
class Sandbag {
private:
sf::RenderWindow* window; //SFML window object
sf::Texture texture; //Sandbag texture
sf::Sprite sprite; //Sandbag sprite
Coord pos; //Sandbag position
public:
void init(sf::RenderWindow *window, std::string texturePath, Coord pos) {
window = window;
if (!texture.loadFromFile(texturePath)) {
std::cout << "Couldn't load the sprite" << std::endl;
}
pos = pos;
sprite.setTexture(texture);
sprite.setPosition(sf::Vector2f(pos.x, pos.y));
std::cout << "One sandbag is constructed." << std::endl;
}
Coord getPosition() {
return Coord(pos.x, pos.y);
}
void paint() {
window->draw(sprite);
std::cout << "One sandbag is drawn." << std::endl;
}
};
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Cyberpunk2077");
Sandbag s1;
s1.init(&window, "bags.png", Coord(20.f,50.f));
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
if ((event.type == sf::Event::Closed) || (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)))
window.close();
}
window.clear(sf::Color::Black);
s1.paint();
window.display();
}
return 0;
}