Search code examples
c++classsfmlstatic-members

Loading a Font in a class in SFML


I'm having trouble loading a font as a static member of a custom class.

I have tried following the SFML tutorial but there are steps that I am clearly missing!

The code is the following:

#include <string>
#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <random>
#include <chrono>
#include <math.h>

using namespace std;
using namespace sf;

class base
{
    int number;
    double radius;
    double last_update_time;
    public:
        static const string FontFile = "SugarpunchDEMO.otf";
        static bool Init(const string& FontFile)
        {
            return font.loadFromFile(FontFile);
        }
        CircleShape shape;
        Text text;
        static Font font;
        void update_number(double time, double &last_update_time, int &number);
        void update_radius(int number, double &radius);
        base(int ini_number, double pos_x, double pos_y, double time);
        void update(double time);
};

The constructor is:

base::base(int ini_number, double pos_x, double pos_y, double time){
    number = ini_number;
    update_radius(number, radius);
    shape.setRadius(radius);
    shape.setFillColor(Color::Red);
    shape.setPosition(pos_x - radius, pos_y - radius);
    text.setFont(font);
    char name[32];
    sprintf(name,"%d",number);
    text.setString(name);
    text.setCharacterSize(200); 
    text.setFillColor(sf::Color::Blue);
    text.setPosition(pos_x,pos_y);
    last_update_time = time;
}

The goal would be to load the font just once and to have it applied to each member of the class.

The error I got is:

In file included from base.cpp:9:0:
base.hpp:19:29: error: in-class initialization of static data member ‘const string base::FontFile’ of non-literal type
         static const string FontFile = "SugarpunchDEMO.otf";
                             ^~~~~~~~
base.hpp:19:40: error: call to non-constexpr function ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
         static const string FontFile = "SugarpunchDEMO.otf";
                                        ^~~~~~~~~~~~~~~~~~~~


Solution

  • This issue has nothing to do with SFML as your error message states:

    in-class initialization of static data member const string base::FontFile of non-literal type

    Or in other words: This way of initializing a class member is only allowed for numerical values and pointers to (string) literals. You're trying to initialize a std::string object of said class.

    As a solution, use const char* for FontFile or move the initialization to your implementation file as const std::string FontFile = "SugarpunchDEMO.otf";