Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: sf::Font Pointer Not Dereferencing  (Read 1530 times)

0 Members and 1 Guest are viewing this topic.

CrouchEndTiger

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
sf::Font Pointer Not Dereferencing
« on: December 26, 2018, 08:58:01 pm »
Hello, I'm relatively new to SFML and find myself stuck on what seems like a simple problem.

I'm trying to store a pointer in a class to a sf::Font defined in main. However, it doesn't seem to be dereferencing properly, or is perhaps pointing to NULL? - although, if it is, I can't work out why!

Any help would be massively appreciated.

Here's a small amount of code which reproduces the problem.

#ifndef __GUARD_FONTSTORAGE
#define __GUARD_FONTSTORAGE
// header file for FontStorage class

#include <SFML/Graphics.hpp>


class FontStorage
{
    public:

        void setFont(sf::Font& new_font) { font_pointer = &new_font; }
        sf::Font getFont() const { return *font_pointer; }


    private:

        sf::Font* font_pointer;    
};


#endif
 

Main function:
#include <SFML/Graphics.hpp>
#include "FontStorage.hpp"

using namespace sf;


int main()
{
    // render the window
    RenderWindow window(VideoMode(800, 500), "Font Testing");
    window.setFramerateLimit(50);

    // store a font in our FontStorage class
    Font font;
    font.loadFromFile("fonts/DejaVuSans.ttf");
    FontStorage font_store;
    font_store.setFont(font);

    // set up some text to test
    Text test_text;
    test_text.setString("Greased lightning! Go, Greased lighting!");
    test_text.setFillColor(Color::Red);
    test_text.setPosition(100,100);
    test_text.setFont(font_store.getFont());
    test_text.setCharacterSize(30);

   

    // main loop
    while(window.isOpen())
    {
        //Poll events
        Event event;
        while(window.pollEvent(event))
        {
        if(event.type == Event::Closed)
            window.close();
        }

        // draw to the window
        window.clear();
        window.draw(test_text);
        window.display();
   
    } // end main loop


    return 0;
}
 

Nothing displays with the above code, but if you set the font directly rather than through the FontStorage instance, it displays fine.
« Last Edit: December 26, 2018, 09:08:54 pm by CrouchEndTiger »

FRex

  • Hero Member
  • *****
  • Posts: 1848
  • Back to C++ gamedev with SFML in May 2023
    • View Profile
    • Email
Re: sf::Font Pointer Not Dereferencing
« Reply #1 on: December 26, 2018, 09:45:52 pm »
Your getFont() returns a copy instead of a (const) reference.
Back to C++ gamedev with SFML in May 2023

CrouchEndTiger

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Re: sf::Font Pointer Not Dereferencing
« Reply #2 on: December 27, 2018, 10:23:18 am »
Wicked, that's it.

Thanks!!

 

anything