Calling class methods before the initialiser?

Hi all,

I have been learning SFML, and have got stuck. The tutorial (http://www.sfml-dev.org/tutorials/1.6/graphics-sprite.php) says the following:

There are a lot of good designs which take care of image management. For example, if you have a class which instances will always use the same image, you can simply do this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Missile
{
public :

    static bool Init(const std::string& ImageFile)
    {
        return Image.LoadFromFile(ImageFile);
    }

    Missile()
    {
        Sprite.SetImage(Image); // every sprite uses the same unique image
    }

private :

    static sf::Image Image; // shared by every instance

    sf::Sprite Sprite; // one per instance
};


What this code seems to say is load the image into a static variable, then every time an object is made it will use the same static image and thus you've saved memory as you don't have to load the image every time.

However, in trying to replicate this, I've come across the issue. Surely the "Init()" function has to be called before the constructor? How would I go about doing this, if at all, as surely the point of a constructor is that it's called first?
Last edited on
Since the Init function is static it can be called even before any Missiles exist using

Missile::Init(imagefile)
Thanks for that, seems to have partially resolved my problem, but now when I try to compile I get the following:

/tmp/ccdrmEHx.o: In function `Missile::init(std::string&)':
missile.cpp:(.text._ZN7Missile4initERSs[_ZN7Missile4initERSs]+0x14): undefined reference to `Missile::image'
/tmp/ccdrmEHx.o: In function `Missile::Missile()':
missile.cpp:(.text._ZN7MissileC2Ev[_ZN7MissileC5Ev]+0x1e): undefined reference to `Missile::image'
collect2: error: ld returned 1 exit status


(I renamed 'Image' to 'image' because using uppercase gave a compiler warning).
Last edited on
You need to instantiate the static variable.

Put this globally in missile.cpp:

1
2
3
#include // whatever stuff you include

sf::Image Missile::image;  // <- add this line 
> Since the Init function is static it can be called even before any Missiles exist using
However, you could forget to call it.
Thanks, that's done the trick.

I'd be very grateful if you could perhaps explain why this is necessary, but I'll mark the issue as solved for now.
Topic archived. No new replies allowed.