A Brief C++ Tutorial
Author: Conor Henderson, University of Alabama (August 2011)
This tutorial is intended to be a simple introduction to C++. It focuses on the most useful aspects of the language for getting started with High-Energy Physics software as quickly as possible. It's not meant to be a fully complete course in C++, so I strongly recommend that you also consult a good C++ book; also useful are the tutorials available online at www.cplusplus.com
The tutorial is intended to be used on a linux system, with access to the gcc compiler suite. Editing the program files can be done with a text editor like emacs, which has a 'C++ mode' that can help with consistent indenting, code highlighting, and other useful features specific to the language.
For instructions on how to compile and run the programs here, see Compiling Programs in this C++ Tutorial
The programs themselves are annotated with lots of comments explaining what is going on.
This tutorial is intended to be a simple introduction to C++. It focuses on the most useful aspects of the language for getting started with High-Energy Physics software as quickly as possible. It's not meant to be a fully complete course in C++, so I strongly recommend that you also consult a good C++ book; also useful are the tutorials available online at www.cplusplus.com
The tutorial is intended to be used on a linux system, with access to the gcc compiler suite. Editing the program files can be done with a text editor like emacs, which has a 'C++ mode' that can help with consistent indenting, code highlighting, and other useful features specific to the language.
For instructions on how to compile and run the programs here, see Compiling Programs in this C++ Tutorial
The programs themselves are annotated with lots of comments explaining what is going on.
A First C++ Program
Your first C++ program is a simple one which just prints "Hello world!" to the terminal screen when you run it. The program code has comments explaining each element of the code and what it does. To compile and run this program on your system, see Compiling Programs in this C++ Tutorial
|
|
Introducing Basic C++ Features
This program introduces most of the basic data types in C++, and the control functions such as if/else and for-loops. As well as being example code, the program has comments that try to explain what is going on.
|
|
Using Functions in C++
This example illustrates how to use functions in C++
|
|
Using Structs in C++
'Structs' are a useful and simple way in C++ to group together related variables. In a sense, this is the first step towards object-oriented programming. Here is an example showing how to use structs.
|
|
Working with C++ Classes
Up to this point, you have only been using features of the C++ language that were basically already present in its fore-runner, C. Now we will start to explore the main feature which makes C++ so powerful: its support for classes and object-oriented (OO) programming.
Let's say we want to write a program involving particles, and each particle will have a mass and a momentum. In BASIC-style programming, we would probably create a whole list of variables to contain the mass and momentum of each particle we are dealing with. In OO programming, we instead try to think about structuring the program around the objects that we would want to work with. We have a physical concept of a particle as something with mass and momentum - it would be nice to be able to create a 'particle' in our program as an object with mass and momentum. We can do this using a 'Particle' class.
To implement our new 'particle' class in C++, we need to create a 'header file' Particle.h and an implementation file (or source code) Particle.cc. Examples are given below.
The header file Particle.h contains the declaration of the class. Anytime we want to use this class in some program, we include the header file in that program. Including the header file will declare to the program what the Particle class is built of, and what it can do.
The Particle class consists of two members, the variables for mass and momentum. In that sense, it's similar to the struct we created earlier. However, classes are much more powerful than structs, because they can do other things as well. For example, a class can also contain functions. We know how to calculate the energy of a particle from its mass and momentum. We could make that function be part of the class, say GetEnergy(). Then if we created a particle object, we could get the energy of that particle within our program just by doing particle.GetEnergy(). Functions which are part of a class are often called the 'methods' of the class.
The Particle.h and Particle.cc files are commented to explain the syntax of exactly how you construct the class.
Basically, once we have created a class in C++, we can use it in our programs just like it was one of the built-in data types (int, double, etc..). An example of a program which uses this Particle class can be found in particle_example.C.
Now that we are working with classes, compiling our programs will also be a little more complicated. The instructions for doing it can be found in here, under 'Phase 2'. The basic idea is that you first have to compile the source code for the class, to make an 'object file', Particle.o. Then any program which wants to make use of this class, you have to link that program to the object file, to produce a working executable.
Let's say we want to write a program involving particles, and each particle will have a mass and a momentum. In BASIC-style programming, we would probably create a whole list of variables to contain the mass and momentum of each particle we are dealing with. In OO programming, we instead try to think about structuring the program around the objects that we would want to work with. We have a physical concept of a particle as something with mass and momentum - it would be nice to be able to create a 'particle' in our program as an object with mass and momentum. We can do this using a 'Particle' class.
To implement our new 'particle' class in C++, we need to create a 'header file' Particle.h and an implementation file (or source code) Particle.cc. Examples are given below.
The header file Particle.h contains the declaration of the class. Anytime we want to use this class in some program, we include the header file in that program. Including the header file will declare to the program what the Particle class is built of, and what it can do.
The Particle class consists of two members, the variables for mass and momentum. In that sense, it's similar to the struct we created earlier. However, classes are much more powerful than structs, because they can do other things as well. For example, a class can also contain functions. We know how to calculate the energy of a particle from its mass and momentum. We could make that function be part of the class, say GetEnergy(). Then if we created a particle object, we could get the energy of that particle within our program just by doing particle.GetEnergy(). Functions which are part of a class are often called the 'methods' of the class.
The Particle.h and Particle.cc files are commented to explain the syntax of exactly how you construct the class.
Basically, once we have created a class in C++, we can use it in our programs just like it was one of the built-in data types (int, double, etc..). An example of a program which uses this Particle class can be found in particle_example.C.
Now that we are working with classes, compiling our programs will also be a little more complicated. The instructions for doing it can be found in here, under 'Phase 2'. The basic idea is that you first have to compile the source code for the class, to make an 'object file', Particle.o. Then any program which wants to make use of this class, you have to link that program to the object file, to produce a working executable.
Suggested Exercise with Classes
|
|
|
As an exercise to give you some hands-on practice with classes, try to modify the Particle class as follows: instead of the total momentum P, have the class members be the three components of the momentum in cartesian coordinates, px, py, and pz. Then change GetMomentum() to calculate the total momentum from the three components, and add two new methods: GetTransverseMomentum() to calculate the momentum in the transverse plane from the px and py components; and GetPhi() to calculate the azimuthal angle phi (also from px and py). Write a simple program which uses these new functions, and make sure you can compile and run it correctly.
Inheritance
A very powerful feature of C++ is inheritance. This allows us to make a new class inherit from an existing class. The new class will automatically contain the members and methods of the 'parent' class; plus, we can add new members and methods specific to the new class. In the example below, we will create a new class Proton, which inherits from Particle. The idea is that Proton is a type of Particle, so it should contain all the functionality of the Particle class, and on top of that we can add more things that are specific to Proton. For the new class we make a header file Proton.h and an implementation file Proton.cc. You can see from the code comments how Proton is created to inherit from Particle.
An example program which uses this new Proton class is proton_example.C
An example program which uses this new Proton class is proton_example.C
Suggested Exercises with Inheritance
|
|
|
- Protons are particles with positive charge. Add a new member to the Proton class to store the charge of the proton (+1 in units of e), and a new function to return this. Test using this in your program.
- Create for yourself a new class Photon which inherits from Particle, but sets the mass to zero. Then write an example program which uses this class, and make sure that you can compile and run it.
C++ Standard Library Classes
The C++ programming language provides a large number of very useful prebuilt classes that you can use. We have already seen some of them, such as iostream and math. Now we will look at a few others.
(Note: cplusplus.com is a very good reference for using the standard library classes.)
(Note: cplusplus.com is a very good reference for using the standard library classes.)
Using std::vector
We often want to have a collection of similar objects, all of the same type. The C++ class vector is an extremely useful improvement over C-style arrays. You can increase the size of the vector dynamically, and there is a convenient 'iterator' to loop over all the elements of the vector. Here you can find an example: vector_example.C
Note that you can compile this example without having to link any objects or libraries to it. Yet, you are using code from an external class, vector, which has to be supplied to your program somehow. So how is this working? The answer is that classes like vector, being part of the C++ standard library, are basically automatically available to the compiler (in other words, the compiler already knows where to find the relevant library, you don't need to tell it). What's even better about vector is that you can make a vector of anything! It doesn't have to be just numbers, like in the previous example. You can even make vectors of your own classes! |
|
Suggested Exercise with Vectors
Practice using the vector class by making a vector of Photons. Have at least 2 photons, and then loop over them using the vector iterator, and call some function (say, GetTransverseMomentum() ) on each one.
Sorting a Vector
In the algorithm header provided by the C++ Standard Library, there are defined functions which can be used on collections of elements, like a vector. Probably the most useful of these is sort. Here is an example of creating a vector, then sorting the elements in order of size.
Suggested Exercise with sort: if you're feeling ambitious, trying sorting a vector of photons based on the transverse momentum of the photon. (Hint: you will need to define your own comparison function which takes photon1 and photon2 as arguments, then compares the transverse momentum of the two objects. ) |
|
Input and Output
We have seen already how to output to the screen, using cout provided by the iostream library. isotream also allows us to take input from the keyboard, using cin. We can also use iostream to read input from a file, and write output to a file instead of the screen. Examples of these are below.
|
|
|