Const mismatches: 2 overloads have no legal conversion for 'this' pointer
Asked Answered
B

1

25

I'm getting this weird error:

error C2663: 'sf::Drawable::SetPosition' : 2 overloads have no legal conversion for 'this' pointer

I think it has something to do with const mismatches but I don't know where, or why. In the following code I have a vector of shapes and sprites, and when trying to access one of the vectors shapes and calling one of its functions I'm getting the error.

std::vector<sf::Shape> Shapes;
std::vector<sf::Sprite> Sprites;

bool AddShape(sf::Shape& S){
    Shapes.push_back(S); return true;
};
bool AddSprite(sf::Sprite& S){
    Sprites.push_back(S); return true;
};

private:

virtual void Render(sf::RenderTarget& target) const {                
    for(unsigned short I; I<Shapes.size(); I++){
        Shapes[I].SetPosition(
            Shapes[I].GetPosition().x + GetPosition().x,
            Shapes[I].GetPosition().y + GetPosition().y);
        target.Draw(Shapes[I]);
    }
    for(unsigned short I; I<Sprites.size(); I++){
        target.Draw(Sprites[I]);
    }
}

How can I fix this?

Both answered 10/7, 2011 at 4:55 Comment(1)
Obviously it's not obvious.Maudemaudie
U
35

Render is declared with a const after the parameters. This means it does not change its object. Which means, that all of the object's member variables are considered constants within Render, as changing their state means changing the containing object. Assuming Shapes is a member variable, and that SetPosition does change the shape (i.e. not declared as const), you cannot call it within a const member function.

So, remove the const from Render and you'll be fine (you fix your logic, in case it must be const).

Uphemia answered 10/7, 2011 at 5:10 Comment(3)
He can't remove the const; he's deriving from a base class that presumably put that const there to begin with.Goniometer
@Nicol Bolas, how do you know? The OP doesn't say anything about the class that contains Render, does he? And if he does and I've missed that, he'll just have to change the content of Render. You can't change member variables inside a const member function (unless you want to hack your own code, and surprise its users).Uphemia
@Nicol Bolas, well, I didn't know that... But my point still stands - he should change his implementation. It actually makes sense - why would rendering an object change its state? In order to confirm with the base class he's inherited, rendering should not change the object's state. Without me deep diving into the implementation, a possible solution could be declaring a local vector of Shapes, which will be set and passed to Draw. that might not be efficient, but it will solve the const mismatch (local variables are allowed to be changed within const member functions).Uphemia

© 2022 - 2024 — McMap. All rights reserved.