Archive

Archive for the ‘C++’ Category

Singletons

Here’s another little something to keep you entertained while you’re waiting for things to get underway here again (it’ll happen eventually, I promise!).

The Happy Singleton

The Happy Singleton

SFML Coder’s C++ Primer

24.10.2011 1 comment

Hi again! Firstly I want to confirm that I probably won’t be writing many more SFML tutorials until a stable SFML 2.0 is released. Unless – of course – a stable release is still a very long way off!

Anyway, I feel I should provide something in the mean time so I’ve decided to pick up my C++ tutorial series again. As some of you may know, I have already put one or two videos on YouTube on this topic and the blog has a few pages related to it. And don’t worry if you already know C++, as I’m sure many of you do. Hopefully some of the later tutorials will be interesting for you as well – I’ll try to make explanations fairly complete so you’ll still be able to take something from videos.

Now, I have some ideas as to the ‘syllabus’ I’m going to follow. Let me know what you think – anything I’ve missed out, things I should remove until later, or simply a few re-orderings.

  1. Introduction to C++, GCC and Code::Blocks
  2. Hello World! Program
  3. Statements, expressions and operators
  4. Variables and more operators
  5. Conditionals – if, else and switch; boolean variables and operators
  6. Loops – for, while and do while
  7. Functions – arguments and return types etc; inline functions
  8. Larger projects – multiple source files, header files, IDE projects

Integers… and Sheep

22.10.2011 1 comment

Hi there! Was just wasting away my time clicking the ‘random‘ button on xkcd (just joking – time on xkcd is never wasted), when I came upon this programming related sketch which I thought I’d share. Enjoy!

XKCD - Can't Sleep

xkcd - Can't Sleep

Categories: C++, Uncategorized Tags: , ,

Introduction to C++0x

14.08.2011 1 comment

I’ve just recorded a short video introducing you to C++0x. Unless you’ve been living under a rock for the past few years, or don’t have an internet connection (and somehow still frequent my blog) then chances are you know about it anyway. You may well have been reading Dr. Stroustrup’s FAQ, my own C++0x articles, or some of the many other sources available on the new standard.

Anyway, this video is going to be the first in a series that will cover C++0x features in video form, rather than textual. Enjoy!

C++0x Support Chart, and a Revision to Nomenclature

14.08.2011 1 comment
IMG_6348.JPG

Image by The Bob Collective via Flickr; unrelated to post... just added for some fun!

Thought you might like to ssee C++0x support for various compilers. Here is a list for GCC, or you can check out this comparison, which features many of the major compilers: Digital Mars’, Intel’s, Microsoft’s, IBM’s and, of course, GCC.

You’ll see that GCC has better support than many, which is in fact why I’ve recently switched from Microsoft Visual Studio to Code::Blocks and/or Qt Creator. I might post a little more about my experiences thereof at a later date. In particular, notice that both MSVC and GCC support long long and nullptr (about which I posted late yesterday). Indeed, long long has unanimous support across all the compilers mentioned in the chart.

And what about the last part of the title? Well I’ve been continuing to say C++0x (and probably will still do so), but as we can expect it’s release sometime this year, I guess I should start saying C++11. Ah well, I probably won’t. That is all.

Two Small C++0x Features

I’m going to mention two little C++0x features today. I don’t have much time, but I thought I may as well share them briefly. They’re both fairly small and quick to explain, so let’s get to it. I’ve put the one that’s faster to discuss first. As always, check out Dr. Stroustrup’s FAQ for more information.

I. long long Integers

The C++0x standard has a new type – the long long integer – which is guaranteed to be at least 64bit. No more annoyances because too many compilers make int and long int the same size – use long long int and you can be sure that you’ll get 8 whole bytes of integral goodness!

Apparently this feature was already supported by a number of compilers, but it’s standard now so you don’t have to worry about non portable code (well you do, but you can blame compiler vendors for being slow to comply with the new standard… ;) ). There’s really not much to say here, merely that you have two 64bit types: long long (i.e. long long int) and unsigned long long (i.e. unsigned long long int). Also note the new literal suffixes: LL for long long and ULL for unsigned long long.

II. nullptr

This one’s exactly as the name suggests: that is, the nullptr keyword represents a null pointer. Previously one might have done something like this:

char* name = 0;

In C++0x, however, one can do the following instead:

char* name2 = nullptr;

These two examples have the same result, that is name == name2 would evaluate to true. On the other hand, while we can also assign the value o to an integral type,  we can assign nullptr only to a pointer variable. So the following would yield a compiler error:

int age = nullptr; // compiler error: age is not a pointer

This is all well and good, but it’s quicker to type 0 than nullptr. Why, therefore, should we use the latter over the former? Well the fact is that the double meaning of 0 as the integer 0 and as the null pointer 0×00000000 has the potential to cause problems. Allow me to demonstrate using Dr. Stroustrup’s example. Consider a function f with two overloads:

  • void f(int)
  • void f(char*)

We call f(0). What happens? Well in fact, f(int) is called, but what if we wanted to pass a null pointer to f(char*). Previously we should have had to resort to something like f((char*)0), which is rather undesirable, in my opinion at least (and, presumably in the opinion of committee members!). So, do the right thing and use nullptr to represent your null pointers.

SFML Graphics – Fonts and Text

01.08.2011 12 comments

In this tutorial, I’m going to tell you about another SFML graphics feature – text. By the end, you should be happy loading fonts from files, and using them to display text to the screen. We’ll also briefly discuss the manipulation of text as a graphics object. As we go along, I’ll make some analogies to SFML’s image handling features, to ease the learning process.

The Video

Working with text in SFML

Let’s get straight to it. Open up our Minimal Application project (you know – the one which just created an empty window and cleared it to a constant colour). If you don’t have the source code for this application at hand, you can find it with the corresponding tutorial.

Getting Started

So first, let’s just go ahead and display our first piece of text. Add the following line before the start of your main loop.

sf::Text Text("SFML Coder");

This constructs a text object which contains the text ‘SFML Coder’. Now we just need to display it. Add the following code after the call to sf::Window::Clear(sf::Color&), but before sf::Window::Display(void).

Window.Draw(Text);

And that’s it. Run your app and you should get some text!

But that’s not really it, is it? ;) Sure, we displayed some text, but we should be able to do a whole lot more. Maybe you want to change the font face or size. Maybe you want to scale the text, or apply a colour to it. Maybe you want to apply other transformations to it, such as rotation and translation. Well you can do all these things, and we’ll see how next.

Custom Fonts

Loading a Font

Remember when we worked with images, SFML had two classes: the lightweight and easily copiable sf::Sprite and the resource heavy, slow-to-load sf::Image? Well it’s the same with text. sf::Font does the heavy lifting – loading ‘glyphs’ from font files into memory, while sf::Text worries about drawing things to the screen, without managing the actual pixel data.

Note that this means it’s not advisable to load fonts on the fly and copying of fonts should be avoided where possible. On the other hand, sf::Text can be both copied freely and created mid frame without performance issues.

So. Let’s see how to load a font now. Add this code before you enter the main loop. We’ll create an object of type sf::Font and load a font into it, from the file font.ttf. You’ll need to provide the file font.ttf in the project directory to run your application. Just grab something from your system fonts folder, copy and paste it, and rename it.

sf::Font Font;
if (!Font.LoadFromFile("font.ttf"))
  return 1;

sf::Font‘s default constructor doesn’t do much. The real work happens in sf::Font::LoadFromFile. This function is similar to sf::Image::LoadFromFile: they both return false on failure and true on success, and they both take a single string filename to specify the file from which to load. On failure, we return 1 to end our program signifying failure to the thing that started it (probably the operating system).

Text: The Full Constructor

In fact, sf::Text has a few more parameters in its constructor than we used last time. We passed just one: a constant reference to a string. Now we’ll add an additional two!

sf::Text Text2("SFML Coder", Font, 40U);

The second argument we pass is a reference to a font object. Note that this argument defaults to sf::Font::GetDefaultFont() which returns a reference to a default, inbuilt font which SFML has (Arial). The third argument is an unsigned integer to specify the size of the font. 30 is used by default. (Note the trailing U marks the integral literal 20 as unsigned).

Now replace the line to draw the previous font with this:

Window.Draw(Text2);

And you’ll see that the text is now smaller, and also in whatever font you provided in the directory.

Controlling Text Attributes after Construction

So an object of type sf::Text has a size, a font and a textual string associated with it, which could be set during construction. Such an object also has a style (bold, italic, underlined, normal, or a combination thereof). This cannot be set by the constructor, but it can be accessed afterwards via get/set methods. Indeed the other three things (the text string, the size and the font) can also be manipulated using get/set functions:

  • to access the font (face): sf::Text::GetFont() and sf::Text::SetFont(const sf::Font&)
  • to access the font size: sf::Text::GetCharacterSize() and sf::Text::SetCharacterSize(unsigned)
  • to access the text string: sf::Text::GetString() and sf::Text::SetString(const sf::string&)
  • to access the style: sf::Text::GetStyle() and sf::Text::SetStyle(unsigned long)
Note that all the text styles are located within the enumeration sf::Text::Style. For example, let’s create a third sf::Text, using it’s default constructor and then setting it’s properties using set methods.
sf::Text Text3;
Text3.SetFont(Font);
Text3.SetCharacterSize(20U);
Text3.SetString("http://www.youtube.com/sfmlcoder/");
Text3.SetStyle(sf::Text::Bold | sf::Text::Underlined);

Manipulating Text

Now sf::Text is derived from sf::Drawable, just like sf::Sprite. That means that all the manipulations we could perform on a sprite (translation, rotation, scaling and applying colours) can equally be applied to a text object. You can get and set its position using sf::Drawable::GetPosition() and sf::Drawable::SetPosition(const sf::Vector2f&) respectively. Similarly, there are functions for rotation and scaling, as well as relative transformations. Then you can use sf::Drawable::SetColor(const sf::Color&) to apply a colour to the text.

I shan’t say too much more on this subject, as I provided some examples in the Images and Sprites tutorial, and you can also read more here. Just remember, of course, that all these manipulations are applied to the sf::Text object and not the sf::Font object.

Here’s a brief example of possible manipulations applied to our last sf::Text object.

</p>

<pre>Text3.Move(400.0f, 300.0f);
Text3.Scale(2.0f, 1.8f);
Text3.SetColor(sf::Color(255, 0, 0));</pre>
<p style="text-align: justify;">

Complete Source Code

Below is the complete source code for this tutorial.

#include <SFML/Graphics.hpp>

int main()
{
	sf::RenderWindow Window(sf::VideoMode(800, 600, 32), "SFMLCoder Tutorial - Text and Fonts");

    sf::Text Text("SFML Coder");

    sf::Font Font;
    if (!Font.LoadFromFile("font.ttf"))
        return 1;
    sf::Text Text2("http://sfmlcoder.wordpress.com/", Font, 40U);

    sf::Text Text3;
    Text3.SetFont(Font);
    Text3.SetCharacterSize(20U);
    Text3.SetString("http://www.youtube.com/sfmlcoder/");
    Text.SetStyle(sf::Text::Bold | sf::Text::Underlined);

    Text3.Move(400.0f, 300.0f);
    Text3.Scale(2.0f, 1.8f);
    Text3.SetColor(sf::Color(255, 0, 0));

	while (Window.IsOpened())
	{
		sf::Event Event;
		while (Window.PollEvent(Event))
		{
			switch (Event.Type)
			{
			case sf::Event::Closed:
				Window.Close();
				break;
			default:
				break;
			}
		}

		Window.Clear();
		Window.Draw(Text); // replace with Text2 or Text3 to display them instead
		Window.Display();
	}

	return 0;
}

C++ Renaissance: The “Going Native” Channel

Check out this post on Herb Sutter’s blog: it provides links to a new series of videos on MSDN all about native coding, particularly in C++. Enjoy!

C++ Renaissance: The “Going Native” Channel.

Categories: C++, C++0x, News

Overloading Template Functions

Another little tip inspired by a question on cplusplus.com. How do we overload template functions? Well the answer is that we overload the template function in the same way as we would overload any other function.

template <class A> void foo()
{

}

template <class A> void foo(float f)
{

}

We do, however, have to be slightly more careful with specialised functions. If we overload a specialised function, the overload must match some overloaded version of the template.



template <class A> void foo()
{

}

template <class A> void foo(float f)
{

}

template<> void foo<int>() // allowed: matches the first template
{

}

template<> void foo<int>(float f) // allowed: matches the seconds template
{

}

template<> void foo<int>(const char*) // not allowed: does not match any template
{

}


C++ Tip – this

You probably all know about the this pointer already, but I just answered a question about it on cplusplus.com, so I thought that I may as well post here while it’s at the forefront of my mind!

So this is a keyword which we can use inside a member function. It is a pointer to the instance of the class from which the member function was called. Still not sure? Check out the following example program.

#include <iostream>
class foo {
public:
   void bar() { std::cout << this << std::endl; }
};

int main()
{
   using namespace std;
   foo foo1, foo2;
   cout << "foo1\n" << &foo1 << endl;
   foo1.bar();
   cout << "foo2\n" << &foo2 << endl;
   foo2.bar();

   return 0;
}

This program yielded the following output for me.

foo1
0031F916
0031F916
foo2
0031F917
0031F917

For you, the actual numerical values of the addresses may be different, but the point is that the address of foo1 is the same as the value printed by foo1.bar() (which prints the this pointer) and the address of foo2 is the same as the value printed by foo2.bar().

So, if you couldn’t before, you can now hopefully understand what I mean when I say that the this pointer points to the instance of the class from which the member function was called.

Interesting Point: Notice that the address of foo1 is only 1 behind the address of foo2. We created the two variables on the same line as stack variables, so they are in adjacent memory locations. However, as the classes are effectively empty, the memory locations are in fact even consecutive (each instance takes only one space on the stack).

Notes
  1. Remember that this may only be used from inside member functions (think about it – it wouldn’t make much sense anywhere else)
  2. this cannot be used in a constructor’s initializer list, but it can be used in its body
  3. this can be used in a destructor’s body, but be careful as if the class is being destroyed you probably don’t want to go around handing its address out to other functions and variables
Follow

Get every new post delivered to your Inbox.

Join 72 other followers