Document Sample
cpp_revision Powered By Docstoc
					                      3d Graphics Programming – C++ Revision – Daniel Livingstone

C++ Revision
These notes will briefly cover some aspects of C++ that you should be familiar with
before taking the class “Real Time 3D”.
Tutors will endeavour to provide additonal support in the lab, but making yourself
familiar and comfortable with the material summarised here is your responsibility.
These notes end with supplementary notes on other aspects of C++ that you may
not have met yet – but which are well worth learning. C++ is a rich and complex
language, and covering all the features in class would not leave enough time to
actually teach much of anything else. What we cover in class is just the beginning –
if you genuinely want to become a programmer you will need to put in the extra
hours required.

1. Fundamentals
Books and Web resources
If you are relatively new to C++ or if you think you need additional practice to
support your revision, I recommend the following book:

      Beginning C++ Through Game Programming, 2nd Edition by Michael Dawson

It is not enough to read a programming text book, to learn effectively you need to
attempt the exercises too – the only way to learn programming is by programming!

A more comprehensive C++ book is:

      Big C++ by Horstmann & Budd. 2004 or 2010 edition – both editions are very
      overpriced, but widely available second hand or via Amazon marketplace at
      much more reasonable cost.

The tutorial at provides good coverage of most of the topics listed

Using your IDE of choice
Labs are equipped with Visual Studio 2010, possibly with Visual Studio 2008, and
also Eclipse. Working at home you may use these or any of a wide variety of C++
IDEs or compilers – including the likes of XCode and Visual Studio Express.
Most code used in the labs should be portable and work on any modern compiler –
but it will be up to you to ensure that you install any additional required libraries.
We will be using the examples and libraries used in The OpenGL Superbible 5th
edition in this class.
You can download the library files and example code from:

Instructions for installing the libraries and examples (for Visual Studio 2008 and
Xcode) can be found on pages 49-61 of The OpenGL Superbible 5th Edition, and on
the Blackboard pages for 2D Graphics Programming.

Most students in this class will have used OpenGL in the 2D Programming class. If
you have not previously used OpenGL you should be able to catch up – and some
revision material will be available on Blackboard. You will have to catch up on the
basics of programming with OpenGL in your own time – but some support is
available. Please contact your lecturer.
                      3d Graphics Programming – C++ Revision – Daniel Livingstone

C++ Pre-test
This following sections include a number of exercises to test your C++
programming. If you are unable to complete these exercises, then you are likely
unprepared for this class – please ask your lecturer for advice.

0. Creating an empty console project in Visual Studio
Not C++ per se, but pretty essential all the same! Visual Studio likes to enhance
programs with additional options that we will not be using – so the first thing you
need to be able to do is to create an empty console project in visual studio.

The exact instructions for this depend on the version of VS you are using – but you
will have to create a new project of type C++ Console, and then select project
options to create an empty project. Ask for help in the lab if you are unsure how to
do this.
Replace with your own IDE if not using Visual Studio!

1. Essential C++ - Syntax, Structured Programming
You should be able to create simple structured C++ programs, utilising functions,
parameter passing, iteration (loops) and selection (if/else). You should also be able
to use the C++ Standard Library, and be able to use online or printed references to
support your use of the Standard Library.
The exercises which follow will require use of a variety of structured programming

2. Strings, Strings and Strings
The C programming language uses arrays of type char for strings of text, and these
are often used in C++ programs. The C++ standard library also provides a string
class ( ). And a common
programming exercise for learner programmers is to develop their own version of
the string class.
Of these, you should be using the standard library string class. Developing your own
string class is useful as a learning exercise, but in practise a hand-made version of
this important class is likely to less fully featured, less well optimised and more
likely to break than the version found in the standard library.

The data structures exercise (below) will allow you to practise working with string.

3. Keyboard, Screen and File I/O
C++ i/o works somewhat differently from that used in C, Java or other
programming languages. All i/o (whether to screen, from keyboard or to or from a
file on disk) is treated as being a stream of characters or binary data. A program
can insert data into a stream, or extract data from a stream. Some streams (e.g.
screen) are write only, some (keyboard) are read only, and some can support both
read and write (e.g. files on disk, depending on file mode).

More information and revision exercises are available at

I/O and strings Exercise:
Write a short program that reads in a short text file (you will have to create this
yourself) input.txt and then asks the user for a word. The program will then output
                      3d Graphics Programming – C++ Revision – Daniel Livingstone
the number of times that word appears in the text. Your program should repeatedly
ask the user for a new word to search for – but should only read in the text file once
at the beginning of the program.
Your solution should use the standard library string class.

4. Data Structures – Structs and Classes
You will need to be able to:
    create C++ solutions which utilise structs and classes where appropriate
    create classes comprising of data and methods, and which use set and get
      methods to provide access to the object data
    build a C++ program using multiple files – with different header (.h) and
      implementation (.cpp) files for each class
    use #include to include your own and library header files
    use #ifndef, #define and #endif in header files to prevent compilation
      errors when a header file is included in multiple other source/header files (or
      alternatively is supported by your compiler: #pragma once).

Class and Objects Exercise:
Create a weapon class to be used in a simple role-playing game. Weapon objects
need to be able to store information about how much damage a hit from the
weapon does, the value and weight of the weapon, and a brief description. Include a
short test program in main which creates several weapons and displays the details
of each. The submitted solution should be a zip containing three files – main.cpp,
weapon.h and weapon.cpp Do not submit the complete project folder! In particular,
DO NOT submit the debug or intermediary project files which can be very large.

5. Class Diagrams
Class diagrams are a simple approach to illustrating Object-Oriented designs and
implementations. While OO design is a sizeable topic in its own right, the
fundamentals for creating class diagrams are very straight-forward – with each class
simply represented by a box in three sections. The top section simply contains the
name of the class, the middle section lists the data members of the class and the
bottom section lists the methods of the class. More detail can be shown than just
this, but the basic idea is very simple. The diagrams themselves are a very useful
(and very widely used) means of documenting software designs.
There are many books in the university library which provide more detail on
creating class diagrams, and some useful online resources including:
                       3d Graphics Programming – C++ Revision – Daniel Livingstone
The picture above shows a class diagram being edited using the free online diagram
editing tool gliffy, showing an partially complete Appointment class. Other free
tools include StarUML and GreenUML. GreenUML features good integration with
Eclipse allowing the automatic creation of code-stubs from a class diagram and the
creation of class diagrams from code.

6. Arrays and Pointers
You should be able to:
    use arrays to store multiple data elements of a single type
    use pointers to objects along with the keywords new and delete to
      dynamically create objects of a given type
    use pointers to iterate over the data in an array (as an alternative to using
      array subscripts)

In particular, you will need to be comfortable with the reference (&) and
dereference (*) operators.

Example: Read the following code – can you work out what the output will be? Try
compiling and running the code – do you get the output you expected?
#include <iostream>
using namespace std;

void test1(int &val) // passing by reference
{      cout << "Test1 ++val = " << ++val << endl; }

void test2(int val) // passing by value
{      cout << "Test2 ++val = " << ++val << endl; }

void test3(int *pval) // passing by pointer
{      cout << "Test2 ++value = " << ++(*pval) << endl; }

int main()
       int a, *b, c; // a and c are of type int, b is a pointer to an int
       a = 25; // a is now equal to 25
       b = &a; // b now points to a
       c = a; // c now contains the value 25
       *b = *b + 1; // what will this do??
       cout << "a = " << a << ", b = " << *b << ", c = " << c << endl;

      int value, *pvalue;
      value = 99; pvalue = &value;

      cout << "Pre-test value = " << value << endl;
      cout << "Post-test value = " << value << endl << endl;

      cout << "Pre-test value = " << value << endl;
      cout << "Post-test value = " << value << endl << endl;

      cout << "Pre-test value = " << value << endl;
      cout << "Post-test value = " << value << endl << endl;

      return 0;
                      3d Graphics Programming – C++ Revision – Daniel Livingstone

7. Dynamic Arrays
You should be able to:
    Use dynamic arrays to create arrays where the size of the array is not known
      until run time

Dynamic Arrays Exercise:
Write a short program which first asks the user how many numbers are to be
entered. The program should then create an array of that size repeatedly ask for an
integer to enter into the array until it has been filled.

8. Inheritance, Polymorphism, Encapsulation
Inheritance, polymorphism and encapsulation are fundamental concepts of all
object-oriented programming languages.
You should be able to explain what each of these terms means, and what
significance each has for software development.

Virtual Function Calls and Abstract Classes
Polymorphism relies on some behind-the-scenes magic of a virtual function table
(aka virtual method table). There is some run-time overhead and cost associated
with this, and it is worth having an understanding of what is actually happening
when you put polymorphism into action.
See e.g.

In OO, an Abstract Class is one which cannot be used to instantiate objects – but
which can be used to inherit from. Descendent classes may be either abstract or
concrete. In C++, an abstract class is any class containing one or more pure virtual
functions. A pure virtual function is a virtual function without an implementation
             class AbstractThing {
               virtual void function() = 0;

Inheritance & Polymorphism Exercise:
Characters in the RPG (from 4, above) should be able to carry a range of items –
treasure and weapons. Each item of treasure needs a description, value and weight,
while each weapon needs a damage value as well as a description, value and
Use inheritance to create a test app which creates a small array which is able to
hold both treasure and weapons (as a building block for creating the inventory
system for the RPG). Test this by inserting a mixture of items, and then by iterating
through the array outputting each item's details to screen in turn.
Rather than have Weapon inherit from Treasure, a better solution may be to have
both classes inherit from some more generic InventoryObject class. Can you think
of any other possible object types that might be found in an RPG?
To submit your solution, create a zip of the source code files – a main.cpp file and a
.h header and .cpp implementation for each class.

9. Constructors
While not always required, failing to provide your own custom constructors can limit
the flexibility of classes. A default constructor is always applied if you do not provide
your own, but this might not be suitable for all purposes.
                      3d Graphics Programming – C++ Revision – Daniel Livingstone
More information here:

10. Miscellaneous
While I've collected these topics together, don't take it to mean that these are not
important! Indeed, any competent C++ programmer should have a reasonable
grasp of all of these topics.
Static Members
Public, Private and Protected modifiers
Scope and Namespaces
Preprocessor Directives
Debug and Release Modes

These are all covered in books and online source ( such as ), and all
are worth learning

Submit Your Solutions
You should submit your solutions to all the exercises in these notes on Blackboard
AND have your solutions in class for the week 2 lab. (Either on your network home
drive or by bringing your programs to class on a memory stick).

To submit on Blackboard the following steps are required:
    Zip source code files for each project into a single zip file.
    Do NOT include intermediary project files or debug/release folders. A Visual
      Studio project with just a few KB of source code can create many MB of
      project files. It is OK to include .sln and .proj files, though.
    You will need to be registered on the module in Blackboard. I hope to be
      able to ensure that everyone is enrolled by the end of week 1. Email me if
      you are having problems.
    In the course page on Blackboard go to the Digital Dropbox. You need to add
      files AND 'send' them before they are submitted.
                      3d Graphics Programming – C++ Revision – Daniel Livingstone

Next Steps
Over the course of this class we will also try to cover the following additional C++

Function & Operator Overloading
Function overloading is a feature of C++ (but not C) that allows multiple functions
to share the same name as long as they each take different parameter lists of input.
This is important as otherwise the compiler would not be able to identify which
version of a function was needed.

So it is possible to have a getMax function that takes two integers as input, and
another that takes two floats.

Operator Overloading allows programmers to define new functionality for C++
operators ( *, /, +, -. ++, etc.). This is used in classes to allow programmers to
implement a version of the operator for that class. For example, if we create a class
for geometric Vectors, then we probably want to be able to add and subtract them.
Instead of having to write:
It would be much more natural to write:
       vector1 += vector2;

To implement this, the vector class would have to include a method to overload the
+= operator:

const Vector2d& Vector2d::operator+= ( const Vector2d& v )
      x += v.x;
      y += v.y;
      return *this;

The const keyword can be used when declaring a variable to indicate that the
variable is a constant – and cannot be changed. If you look at the code above you
will see that it has other uses too. When applied to a parameter input to a function,
const informs that compiler that the input value should not be changed by the
function. This can help trap errors – as any attempt to change the input value in the
function will result in a compile error.
The other use of const indicates that the value returns by the function is itself a
const – and cannot have its value modified.
This prevents the following from compiling:
       ( vector1 += vector2 ) += vector3 \\ add v3 to the result of adding v2 to v1

It can, however, be assigned to another variable, and that can then be modified,
       vector3 = (vector1 += vector2) \\ assign the result of adding v2 & v1 to v3
       vector3 += (vector1 += vector2) \\ add (result of adding v2 & v1) to v3
                      3d Graphics Programming – C++ Revision – Daniel Livingstone
const is also used to declare constant member functions – this is a clear sign to the
compiler that a particular method should not alter any of the data belonging to the
object – and is another very useful way of trapping errors at compile time.

Friend functions
Friend functions are another unusual feature of C++. A friend function (or class) is
given access to the private data and methods of another class. Say for example
you wish to overload the insertion operator ( << ) to make it easy to output your
class to a stream, e.g.:

      cout << vector1 << endl;

You can do this by overloading the operator<< function, and giving the overloaded
insertion operator access to your class data by making it a friend function, adding
something like this to your class declaration:

      friend ostream& operator << ( ostream& , const &Vector );

You should not expect to use the Friend feature often, but minimally you should
understand what is happening when you do see it.
For more examples and explanation, see

Additional Exercises
Additional I/O exercises:
1. Write a simple C++ program to read ten numbers from a file – in.txt – and to
then output the sum of the numbers to screen and to an output file – out.txt
Include basic error handling for conditions where either the data in the text file is
unexpected or the file ends after less than ten numbers.

2. Modify your RPG examples from before to use the friend feature so that Weapon
and Treasure objects can be output simply by insertion into an output stream, e.g.:

      cout << weapon1 << “; “ << weapon2 << endl;

(Can you use polymorphism to output all the weapons and treasures held in the
array by iterating over the array in a loop?)

For Further Study
While the RT3D class focuses on graphics programming with OpenGL, achieving
mastery of the topics listed above does not mean that you have attained mastery
over C++ itself – that will take many more years of study and practice.

Alongside your studies this year it is highly recommended that you also investigate
and start to master the following:

A. Effective Debugging/Bug Hunting
Over many years of observation it has become clear that the normal undergraduate
approach to fixing compilation or run-time errors tends to be somewhat ad-hoc –
almost random in nature. While finding the source of a problem may take some
educated guess-work at times, there are methods to use to help identify the source
of problems. Some helpful tips can be found online:
                      3d Graphics Programming – C++ Revision – Daniel Livingstone

B. Template Functions and Classes
Templates are a powerful feature of C++ that allow programmers to write just one
version of a function or class that is then able to take different types of parameters
as input. For example, a getmax function that can take integers, floats or doubles
(or indeed, any other comparable type) as input.
Templates actually create multiple versions of the templated code at compile-time,
one for each input type required. Some very advanced programming tricks have
been developed using some features of this, but the basics of using template
parameters are quite simple and easy to apply in practice.

Useful link:
Templates Tutorial -

C. The Standard Template Library

The Standard Template Library has been part of the C++ standard for some years
now, but is often missed or ignored. This is a big mistake, as the library contains a
number of very useful elements (containers and algorithms), and judicious use of
the STL can save a lot of work. Minimally, you should learn how to use the STL
vector, a type of dynamic array that can be resized at any time – but a few hours
spent learning the STL can save many many hours trying to recreate functionality
that is already available – and implemented better than you are ever likely to

Useful links: - Stephan T. Lavavej, in charge of Microsoft's implementation
of the STL, introduces and explains the STL in a one hour video
The C++ Standard Library: A Tutorial And Reference by Nicolai M. Josuttis,
Effective STL by Scott Meyers (improving your use of STL once you have grasped
the basics) -
STL reference -

D. Design Patterns
The concepts of Design Patterns apply to a wide range of areas – originally used in
architecture, they have since been applied to software development, a wide range of
engineering areas and even teaching. Fundamentally, Design Patterns recognise
that there are a number of common design challenges in any particular problem
area – and that there will also be a number of tried and tested solutions that can be
applied. Anti-patterns are examples of solutions that are known to be bad in some
A prerequisite for beginning to study design patterns in C++ is a good
understanding of the OO fundamentals – inheritance, encapsulation, polymorphism
and composition. The STL itself makes heavy use of Design Patterns.

Head First Design Patterns in Java by Freeman, Robson, Bates and Sierra provides
good descriptions of most of the core design patterns in a very readable format.
                      3d Graphics Programming – C++ Revision – Daniel Livingstone
Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm,
Johnson and Vlissides is the definitive book on the subject, but the examples are not
as clearly explained or expanded as in the Head First book.

E. Exception Handling
Exception handling (to deal with situations where something goes wrong at run-
time) in C++ requires some effort on the part of the developer – but is necessary in
the development of robust software. Standard C++ only recently added some
standard exceptions, but it is generally still left to the developer of a program (or a
library) to define the exceptions that the program will catch.
The general format for exception handling code is to separate blocks of code that
try something that might result in an error and blocks of code that catch errors,
and do something to sort out the problem so that the program can continue.

F. Further Reading
By now you should have realised that there is a lot to learn about programming with
C++. The following resources are a tiny sampling of the vast number of print and
online resources dedicated to the subject:

Effective C++, Scott Meyers
C9 Lectures with Stephen Lavavej – A series of five (so far) video lectures on The
Standard Template Library
C++ at WikiBooks
Exceptional C++, Herb Sutter

C++ Revision Notes by Daniel Livingstone
with thanks to Peter Bloomfield and Alistair McMonnies for comments

                          This work is licensed under the Creative Commons Attribution-
                          NonCommercial 3.0 Unported License. To view a copy of this
                          license, visit or
                          send a letter to Creative Commons, 171 Second Street, Suite
                          300, San Francisco, California, 94105, USA.

Shared By: