Search code examples
c++inheritanceparameterssfml

Strange effect of passing parameter as `const`


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.


Solution

  • 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.