SFML 2.0 text problem

i am trying to find a quicker way of setting the variables for text. here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
sf::Text set_text_values(sf::Text text, sf::Font font)
{
    text.setFont(font);
    text.setCharacterSize(50);
    text.setColor(sf::Color::White);
    return text;
}

int main()
{ //Hull is a std::string
   Hull = set_text_values(Hull, font);
   //my actual code is alot bigger
}


and i have tried it like this

1
2
3
4
5
6
7
8
9
10
11
void set_text_values(sf::Text text, sf::Font font)
{
    text.setFont(font);
    text.setCharacterSize(50);
    text.setColor(sf::Color::White);
}

int main()
{
   set_text_values(Hull, font);
}


the code compiles and runs but it won't show the text on the screen like it did when i did it manually like this:

1
2
3
4
5
6
int main()
{
  Hull.setFont(font);
  Hull.setCharacterSize(50);
  Hull.setColor(sf::Color::White);
}


what is wrong with it?
You are passing your text and your font by value... which makes them copies. Therefore any changes made to them in the function will not change the objects that you passed in.

1
2
3
4
5
6
7
8
9
10
11
12
13
void func(int v)  // <- v is its own variable
{
    v = 5; // <- this changes v... it does not change any other var
}

int main()
{
    int q = 10;  // <- q is not v
    func( q );  // <- passes q by value as 'v'.  So this is like saying v = q
        // changes made to 'v' will not change 'q' because v is not q

    cout << q; // <- will output 10 because q has not changed.
}


Your function has the same problem as this illustrates. Only instead of your function doing 'v = 5', it's setting the font/size/etc.



If you want to change the object you're passing in... you can't pass by value... you can instead pass by reference:

1
2
3
4
void set_text_values(sf::Text& text, sf::Font& font)
{
    //...
}


Note the added '&' symbols. This means they are references to existing objects, and are not copies of other objects.
right thanks i forgot about using the reference
Topic archived. No new replies allowed.