Search code examples
c++ooppointersfunction-pointerssfml

Set pointer in class


i'm new to c++, and i start a project with SFML. I need a class that can handle sprite, so i do:

#pragma once

#include <SFML/Graphics.hpp>
#include <iostream>
class Particle
{
private:
    sf::Sprite **sprite;
public:
    Particle(sf::Sprite* sprite)
    {
        this->sprite=&sprite;
        
    };
    ~Particle();

    void setPosition(sf::Vector2f newPos)
    {
        **sprite.setPosition(newPos);
    }
};

i want to access certain sprite with pointer, and set that sprite to class private variable, but i meet an error "expression must have class type but it has type "sf::Sprite **". The sprite variable need to be accessed by all the function so, i want to set it locally to this class. Is there a better way to do this?


Solution

  • The error is because

    **sprite.setPosition(newPos);
    

    is the same as

    **(sprite.setPosition(newPos));
    

    That is, you try to dereference what sprite.setPosition(newPos) returns.

    To solve that error (leaving the other problem I already mentioned in a comment) you need to dereference the pointer variable itself:

    (*sprite)->setPosition(newPos);