General C++ Samples

Derived Classes

The derivation of one class from another is the very corner stone of Object Oriented Design. This sample is truly for the beginner.

Friend Classes

Have you ever said to yourself, “I wish I could write poor object oriented code with classes that are hopelessly intertwined and non-reusable”? Well, look no further. The “friend” key word can really let you shoot-yourself in the foot by allowing one class to fiddle with the private data of another class! Ok, I'm being sarcastic. There are actually some good uses for the “friend” key word, but they typically involve fixing other object-oriented blunders.

Constant Member Functions

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. This behavior can be very useful when you want to prevent other programmers on your team, who may be writing functionality for you class, from misusing your class’s private data.

Pure Virtual Functions

Pure virtual functions are virtual functions declared with the pure-specifier (= 0) after the function signature. This special type of function is useful for creating classes, which act only as interfaces and cannot actually be created with out being derived from.

Virtual Function Access

The access control applied to virtual functions is determined by the type used to make the function call. Overriding declarations of the function do not affect the access control for a given type.

Function Hiding

Either intentionally are by accident, it’s possible to hide a function that exists in a base class so that it becomes inaccessible, even when its been declared public within the class.

Function Pointers

This sample demonstrates how to use function pointers to create a dispatch table of functions.

Function Templates

This sample demonstrates how to use templates to reduce the clutter of numerous overloaded functions, which differ only by type, into a single function template.

Forward Declarations

This sample demonstrates how to use forward declarations to compile classes that exist in a cyclic dependant relationship. This basically means that one class can not be compiled unless another one is, but that second class can't be compiled unless the first one is compiled... and around around we go forever!

Quick Sort Algorithm

Quick Sort is a powerful algorithm for sorting arrays of numbers or strings by value through a recursive, divide-and-conquer style attack. If you went to college for Computer Science, then you've already study this, but if your an old-school hacker like me and skipped college, you should definitely add this to your black bag of tricks.

Random Number Generation Within a Range

This sample actually contains two different methods of creating random number within a given range. The first one is typical of most random number generators and simply uses a call to rand() and a modulus operator to place the random numbers within a range. The second is more more advanced and returns a random number which is is chosen by shuffling the elements of a vector which only contains values that exist within the specified range.

Bit Array

Demonstrates how to manipulating an array of chars as if they were an array of individual bits. Very useful when memory is a scarce commodity and you have a ton of variables that are simply acting as Boolean flags.

Passing Variable Arguments to Functions

Demonstrates how to write a function which makes use of a variable argument list like the standard printf( ) function does. Learning this is like learning a new piece of trivia; Interesting, but rarely useful. Maybe you can impress your friends with it... who knows.

Reverse Array Order

Here's a simple function that'll allow you to reverse the order of a char array. Very useful for hard-headed programmers who still refuse to use STL, or college students who just don't know better yet.

Linked List Sample

Here's an extremely trivial example of a singly-linked, linked list suitable for beginners. Each node of the list is very simple and has only a single int as its data. The linked list class it self supports the standard list operations such as adding and removing nodes and navigating through the nodes with typical next and previous commands.

Smart Pointers

Smart pointers automatically free the memory associated with a pointer when that pointer is deleted, which helps to prevent a common source of memory leaks.

Reference Countable Objects

This sample demonstrates how to implement reference counting. Reference counting helps to prevent the types of bugs and crashes caused by "dangling pointers", which can occur when an object is prematurely deleted while other objects are still referencing or using it.

Interface Classes

While pure virtual functions are useful for enforcing an "interface", they should not be confused with a true interface mechanism, which can be found in languages like Java and C#. The reason I point this out is that under certain circumstances there are considerable performance penalties with using pure virtual functions to mimic an interface.

With that said, this sample demonstrates how to create an interface class, without having to use an abstract base class containing virtual calls.

C++ Template Samples

 

Understanding Template Inclusion

This sample demonstrates how the naive attempt to define templates like regular C++ code (separate source and header files) will compile - but fail during the linking stage.

Template Arguments

This sample is an in-depth demonstration of how arguments to template parameters work with respect to instantiation.

Template Concepts

This sample demonstrates how to use template concepts to enforce proper template usage through compile-time errors. In other words, concepts are like rules which check for, or enforce, proper usage at compile-time.

Type Traits

This sample demonstrates how to use type traits to attach additional information to a particular type used by a template.

Template Policies

This sample demonstrates how to use template policies to customize how templates work with certain types.

STL Samples (Standard Template Library)

 

STL's Linked List (list)

This sample demonstrates how to use STL's list container to store a series of int values in a linked list structure.

STL's Variable-length Array (vector)

This sample demonstrates how to use STL's vector container to store a series of int values in a variable-length array.

STL's Double-ended Queue (deque)

This sample demonstrates how to use STL's deque container (pronounced like 'deck') to store a sequence of char values. The sequence is stored as a double-ended queue, which permits the insertion and removal of an element at either end.

STL's Priority Queue (priority_queue)

This sample demonstrates how to use STL's priority_queue container to store both a sequence of sorted int values and a sequence of sorted class instances.

Custom Sort Function

This sample demonstrates how to create a custom sorting routine for STL’s std::sort function so you can use it to sort objects created from your own class types.

As a concrete example, we’ll create a simple record based state management system, which is typically found in 3D rendering systems. We then create a custom sorting routine to use with STL so we can sort our Records by the Textures they use. This will allow us to group together Records that use the same Texture so we can save ourselves the overhead associated with changing the current Texture object.

Design Patterns & C++

 

Factory Design Pattern

A Factory defines an interface for creating an object, but lets subclasses decide which class to instantiate. In other words, the Factory lets a class defer instantiation to subclasses. I know that may not sound too exciting, but I assure you that you're going to see a lot more discussion concerning Patterns like this one as Software Development matures into a stricter Engineering field. If I were you, I would get a jump on it before it's too late to catch up.

Publisher-Subscriber Design Pattern

The Publisher-Subscriber design pattern helps to keep the state of objects synchronized through the one-way propagation of change notifications. This normally entails several objects called "Subscribers" registering with a central object called a "Publisher". When the state of the Publisher changes, the Publisher calls a notification function on each of the registered Subscribers. It's then the responsibility of the Subscriber to examine the Publisher's new state and act accordingly.

Chain of Responsibility Design Pattern

This pattern chains a series receiving objects together, and then passes any event messages from object to object until it reaches an object capable of handling the event. This method of message passing is far less messy than having senders and receivers maintain references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain.

Win32 Specific Samples

 

PerfMon Leak Test

As you may or may not know, PerfMon is a performance analysis tool available on Windows NT, Windows 2000, and Windows XP. If you're familiar with it, you already know how useful it can be, but if you're not, simply click the "Run" button on the "Start" menu, type "perfmon" and click "Ok" to find out... because you're only hurting yourself by refusing to acknowledge it.

This sample demonstrates how one can track memory leaks using PerfMon by using the GlobalAlloc and GlobalFree functions available in the Win32 SDK.

Windows Fast I/O

For most file I/O jobs the typical usage of Win32's CreateFile function will do, but occasionally you're faced with a behemoth file that threatens to throw a monkey wrench into your frame rate by simply taking forever to load up. Part of the problem is when you open a file and begin reading from it, the OS is actually copying your file's contents to a cache buffer before copying it to your local buffer and while this behavior can be handy for smaller files that you may open and close on a regular basis, letting the OS cache your larger data files, which you'll probably only want to load once anyway, is just too slow. In this situation, it is best to totally bypass this cache buffering mechanism and read and write data directly to the file with no middle-man slowing things down. With that in mind, this sample demonstrates Fast sequential IO for Windows by timing the reading and writing of a 1 GB test file using the FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN flags when calling CreateFile. Please note, this code has only been tested on Windows 2000 so far.

Creating Mini-dumps Under Windows

This sample demonstrates how to make use of the mini-dump feature in Windows 2000 and Windows Xp. If you're not familiar with mini-dumps, they're similar to a core dump on a Unix platform. Maybe it will come in handy one day when you're faced with that mother-of-all crash bugs!

Multi-Threaded Programming

Here's another sample of multi-threaded programming for those that feel that debugging regular programs is too boring and yearn for the never ending frustration of shared data corruption and intermittent bugs. Actually, I'm just being a little sarcastic there. Threads are not that terrible, just be careful how you use them or you're going to end up in a world of hurt.

  • Download 3 KB (Last Updated: 09/25/04)

Winsock 2.2 Client/Server Sample

Yeah, I know. It's not quite as interesting as graphics programming, but a good knowledge of TCP/IP socket programming can be very valuable to someone hoping to land a job at a game company, especially if the job has anything to do coding the multi-player portion of their game.

Simple DLL with Test Program (Dynamic Link Library)

While I don’t use DLLs too much myself anymore, many game companies still use them to support modular programming or for creating a library of game related functions for implementing high-level scripting languages, so here you go.

Finding Processes

This topic doesn't sound too exciting unless you've been beating your head against a wall trying to figure out how to do it. To save you the trouble, this sample demonstrates how to find a running process using CreateToolhelp32Snapshot, Process32First, and Process32Next.

Inline Assembly

Demonstrates how to use Visual Studio's ability to intermix assembly code with your own C++ code. Also a great way to break cross-platform compiling of your C++ code and piss-off people attempting to port your PC game to other operating systems.

  • Download 8 KB (Last Updated: 09/25/04)

Customizing C/C++ Applications with Lua

 

Windows Build Environment for Lua

If you haven't already noticed, the source code for Lua doesn't come with a Windows friendly build environment. This download will make it considerably easier to get up and running with Lua if you use Visual Studio .NET 2003.

Note: This build environment was tested against Lua 5.1.2, which I downloaded from here. These workspace and project files may or may not work with other versions of Lua.

Lua Scripting Basics

This download is a basic introduction to scripting with Lua. It demonstrates the basics such as if conditionals, while and for loops, and declaring functions.

Simple Embedded Lua Script

This sample demonstrates the bare essentials of running an embedded Lua script from a C/C++ application.

Relevant Keywords: lua_State, lua_open, lua_baselibopen, lua_dofile, and lua_close.

Calling C/C++ functions from Lua

This sample demonstrates how to register a C++ function with Lua so it can be called by an embedded Lua script.

Relevant Keywords: lua_State, lua_open, lua_baselibopen, lua_dofile, lua_register, lua_gettop, lua_isnumber, lua_pushstring, lua_error, lua_tonumber, lua_pushnumber, and lua_close.

Calling Lua functions from C/C++ applications

This sample demonstrates how to call a Lua function from a C/C++ application.

Relevant Keywords: lua_State, lua_open, lua_baselibopen, lua_dofile, lua_getglobal, lua_pushnumber, lua_pushstring, lua_call, lua_tonumber, lua_pop, and lua_close.

Miscellaneous

 

Custom Scripting Language

This download contains the source for a very simple C like scripting language called "my_c" written with the help of Flex and Bison (better known as Lex and Yacc for you Unix users). A scripting language like this can be added to a game engine or level editor for controlling such things as A.I., Animation, or level events. I'm still working on this one so, as of right now, the language only supports a few basic items such as input/ouput to the console, a string and integer data type, if/else conditionals, value assignment (=), equality testing (==), and an addition operator (+) that not only works on integers but performs smart type conversion and/or string manipulation in statements that mix the two data types together. Of course, in this way, it's more like Java I guess.

You should note that this code doesn't really explain how to use flex and bison, so if you're not familiar with these two programming tools or compiler design in its most general sense, you should check out the scripting tutorial on Flipcode by Jan Niestadt. I basically started my sample using his tutorial's code but, in the end, my code ended up looking very different as I was trying to make a real scripting language - not a toy sample for demonstration purposes.

Game Programming Tests

Like most other programmers in the industry, the long road to my first game programming job, was paved with dozens of uncomfortable interviews, in which individuals both knowledgeable and unknowledgeable questioned everything about me - from my programming skills and experience to the manner in which I indented my code. Of course, some interviews won't even get scheduled until you finish a "game programming test" that their Lead Programmer has so graciously concocted for you. Here's a few that I saved. As you'll soon see, the questions on these things can range anywhere from overly simplistic to, "Whatcha talkin' about Willis?" (Imagine Gary Coleman's voice there for effect).