2

Consider the following classes :

  1. Bullet class
    class Bullet : public sf::Drawable {
    public:
        Bullet(const sf::Vector2f& pos, const sf::Vector2f& dir, 
            const float& speed, const float& time, const float& life_time);
        ~Bullet();
        
        bool collides(const Wall &wall);
    private:
        ...
}

and Wall class

    class Wall : public sf::Drawable {
    public:
        Wall(const sf::Vector2f & endpoint1, const sf::Vector2f& endpoint2);
        void sample();
        ~Wall();
    private:
          ...
}

For some reason, that I can't entirely comprehend, I can not call any methods for the wall parameter of the bool collides(const Wall &wall) method, when the const is present, e.g. if I remove the const, everything works just fine.

I think it might have something to do with inheriting the sf::Drawable, but I am not that experienced with SFML yet.

Can somebody clarify what should I look into to find what is causing this? Thank you in advance.

naomipappe
  • 23
  • 1
  • 5
  • 3
    You can only call `const` methods on `const` objects. If `collides` doesn't change internal state of `Bullet`, you should declare (and define) it like this: `bool collides(const Wall &wall) const;` I suppose there is a duplicate somewhere, will try to find something – Yksisarvinen Jul 02 '20 at 09:50
  • @Yksisarvinen Thank you very much, completely forgot about that. – naomipappe Jul 02 '20 at 09:56

1 Answers1

2

You cannot call an non-const member function on a const object or a reference to a const object, simple as that.

class Wall : public sf::Drawable {
public:
    void sample() const; // <---- you need this
};            

Now it's up to you, either you make member functions that don't change the state be const, or get rid of constness of the parameter of collides.

jrok
  • 54,456
  • 9
  • 109
  • 141