C++ Language Tutorial

In construction

Table of Contents:

This tutorial contains a brief introduction to the C++ language. It is intended as a tutorial on the language, and aims at getting a reader new to C++ started as quickly as possible. It is certainly not intended as a substitute for any of the numerous textbooks on C++.

The best way to learn a new ``human'' language is to speak it right from the outset, listening and repeating, leaving the intricacies of the grammar for later. The same applies to computer languages -- to learn C++, we must start writing C++ programs as soon as possible.

What will help in this challenge is that for the most part, C++ is very similar to C. In fact, C++ evolved out of C. Therefore, the C Language Tutorial applies to C++ in functionality, if not fully in the details of the syntax. Our approach in this C++ tutorial is to first point out the similarities between C++ and C by way of comparison between the two C and C++ tutorials on our course website. Therefore, we will emphasize as much as possible of of the commonality C/C++, and then point out the extensions in C++.

The major differences between the C++ and C languages is that the struct structure in C has evolved in C++ into the concept of classes and objects. To become familiar with these concepts will demand some work from the part of the reader.

The WEB contains numerous tutorials on C++. These can be found via Google searches. We will point to new material on classes to understand these new features of C++.

1. A First Program -- Hello.cpp

The program hello.c in The C Tutorial, like many other C programs, should compile and run under C++.

#include <stdio.h> void main() { printf("\nHello World\n"); }
To compile and run the code under C++, type
	 g++ hello.c -o hello

followed by (to execute the code)


But, most C++ programmers would rather use the native input/output handling functions of C++. This would yield

#include <iostream> void main() { std::cout << "\n" << "Hello World" << "\n" ; }
Save this code in a file hello.cpp, then compile it by typing:
	g++ hello.cpp -o hello

This creates an executable file hello, which is then executed by simply typing ./hello. The result is that the characters Hello World are printed out on the monitor, preceded by an empty line.

A C++ program contains functions and variables. The functions specify the tasks to be performed by the program. The main() function establishes the overall logic of the code. It is normally kept short and calls different C++ (or other language) functions to perform the necessary sub-tasks. All C++ codes must contain a main() function.

Our hello.cpp code calls std::cout << , an output function from the I/O (input/output - keyboard/monitor) through iostream). The details of this I/O sub-system will be re-visited later in this tutorial.

2. Let's Compute

The following program, CPP_sine.cpp, computes a table of the sine function for angles between 0 and 360 degrees.

/************************/ /* Table of */ /* Sine Function */ /************************/ /* Michel Vallieres */ /* Written: Winter */ #include <iostream> #include <cmath> int main( int argc, char * argv[] ) { int angle_degree; double angle_radian, pi, value; /* Print a header */ std::cout << "\n" << "Compute a table of the sine function\n" << "\n"; /* obtain pi once for all */ /* or just use pi = M_PI, where M_PI is defined in math.h */ pi = 4.0*atan(1.0); std::cout << " Value of PI = " << pi << "\n"; std::cout << " angle Sine " << "\n"; angle_degree=0; /* initial angle value */ /* scan over angle */ while ( angle_degree <= 360 ) /* loop until angle_degree > 360 */ { angle_radian = pi * angle_degree/180.0 ; value = sin(angle_radian); std::cout << angle_degree << " " << value << "\n" ; angle_degree = angle_degree + 10; /* increment the loop index */ } return 0; }

Note how similar this C++ code is from the corresponding C code in The C Tutorial. The only differences between the codes occur in specifying the writing the results to the screen. iostream and std::cout << are used instead of and printf() .

The C++ and C versions of this code are packed in this tar file: C_CPP_Codes.tar. Details pertaining to the use of cout << will be discussed later.

3. Loops

The implemention the for and while loops in C++ and C are identical.

4. Symbolic Constants

Constants of any type can be defined by using the #define compiler directive. Its syntax is simple -- for instance
#define ANGLE_MIN 0
#define ANGLE_MAX 360
would define ANGLE_MIN and ANGLE_MAX to the values 0 and 360, respectively. C distinguishes between lowercase and uppercase letters in variable names. It is customary to use capital letters in defining global constants.

The use of global definitions of constants is identical in C and C++. Both C and C++ also support the const specification for constants. The syntax would then be.

const int N=25;

5. Conditionals

The use of conditionals, boolean operators, switch and nested constructs based on these, is all the same between C and C++.

6. Pointers

Pointers are used in C++ in the same way as in C. For instance, the pointer demo code in the C tutorial would work under C++ with few straightforward minor modification to allow the use of cout << as shown below.

#include <iostream> int main() { float x, y; /* x and y are of float type */ float *fp, *fp2; /* fp and fp2 are pointers to float */ x = 6.5; /* x now contains the value 6.5 */ /* print contents and address of x */ std::cout << "Value of x is " << x << " address of x " << &x << "\n"; fp = &x; /* fp now points to location of x */ /* print the contents of fp */ std::cout << "Value in memory location fp is " << *fp << "\n"; /* change content of memory location */ *fp = 9.2; std::cout << "New value of x is " << *fp << " = " << x << "\n"; /* perform arithmetic */ *fp = *fp + 1.5; std::cout << "Final value of x is " << *fp << " = " << x << "\n"; /* transfer values */ y = *fp; fp2 = fp; std::cout << "Transfered value into y " << y << " and fp2 " << *fp2 << "\n"; }

7. Arrays

Arrays in C++ are handled exactly as in C, except that new simplified statements are provided for dynamic memory allocation (malloc). For instance,

int N = 123; int* buffer; buffer = new int [N]; ... (use buffer for whatever) delete[] buffer;

8. Character Arrays

In construction

9. I/O Capabilities

Simple formatting of output stream is often considered complicated in C++. Thus the production of well aligned tables of results is often considered not to be worth the time spent either. But, obviously, simple formatting of output streams is often needed.


It should be expected that the I/O operations in C++ are done via classes. The advantage of classes in this context in the adaptability of commands like cout to handle diverse sort of variables automatically. For instance, printing via cout an int, a double, a string and a print control with no formatting,

cout << i << e  << "Hello" << "\n"
would likely be impossible in C.


The most important formatting issues in scientific programming are concerned with the width of the fields, the number of decimals (float,double), and the position of the fields. wikipedia lists and briefly describes the classes responsible for I/O in C++. iostream is the I/O header file for cin, cout, cerr and clog. cout, cerr and clog are objects (instantiating of) of type ostream and cin an object of type istream. Three methods ( width(), fill() and precision() ) and manipulators ( among others endl, ends, flush, ws, showpoint, ... ) are used in formatting I/O.

The cpp_tutor describes the formatting of the output field via well chosen, albeit somewhat complicated, cases. It constitutes a good guide to C++ I/O. Some of the examples were extracted in format_examples.tar . Expand the tar file. Then use make all, make test and make clean to run these example codes.

I/O from/to files

C++ obviously allows data set to be written in files that will be read by other codes (possibly under other OS than Linux) later. These data sets do not need to be written with elegance in mind. Accuracy and speed are what is needed here.

The classes needed here are ofstream to writes on files, ifstream to read from files and fstream to read from / write to files. files gives very simple and clear examples of codes that I/O on files. Additional examples can be found in CPP_IO.tar. The file README in the tar file gives some explanations concerning these codes.

Note the use of methods, like open() and close(), to control the reading/writing the data from/to files in the examples above. The tutorials also explain how to use the binary flag in conjunction with ios to read/write the data in binary form for larger data transfer rates. There are also two member functions, read() and write() to read and write in binary format.

10. Functions

In construction

11. Command-line Arguments

The Command-line Arguments are handled exactly the same way in C++ as in C. However, >C++ string variables should be used for consistency.

12. Classes and Objects

For the most part, C++ is very similar to C. C++ is sometimes described as an expanded version of C. Therefore, the idea that C++ can be learned most effectively via a comparison of C++ to C. This C++ tutorial is written to emphasize the similarity of C++ to C.

But a major difference between the C++ and C languages is that the notion of struct in C has evolved in C++ into the concept of class and objects. This will require careful attention from the part of the learner. This section of the C++ Tutorial has no counterpart in The C Tutorial.

The WEB contains numerous tutorials on C++. These can be found via Google searches. Much material exists on the concepts of classes and objects,

Classes and objects are at the basis of the power of C++. Historically, and logically, they are an extension of the struct in C. A struct in C is defined according to the following syntax.

struct my_structure{ int data1; double data2 }
where the members of the structure, data1 and data2, can be of any predefined types (int, double, char, ...) or other struct and in any order and/or number.

This notation can be simplified. For instance,

	typedef struct my_structure foo;
will allow to use the notation
	foo.data1 = 6;
	foo.data2 = 13.7;
to define the members of the foo structure.

This notation can be further simplified as in the following code snippet.

typedef struct my_structure{ int data1; double data2 } foo; foo widgets[5]; for( int i=0 ; i<5 ; i++ ) { widgets[i].data1 = 2*i+1; widgets[i].data2 = 55.89*i; }

C++ makes classes and objects out of C >struct's. It does so by allowing visibility properties for the members to be specified, by allowing members to be functions, and many more.

A quick search in Google (search for "classes in C++") brings millions of hits. The following sites cover some of the most important learning sites and address many of the most important issues of the classes and objects in C++.

C++ tutorial is a very simple introduction to classes in C++. It emphasizes the syntax of a class, the data and methods, their visibility, and the different types of constructors. It deals with objects which are instantiations of classes. It also illustrates operator over-loading. It uses a rectangle as an intuitive example of a class. It may well be one of clearest exposure on classes and objects.

The Wikepedia sites are always likely to be useful. C++ classes is particularly clear in its comparison to C struc, the syntax in building C++ classes, operator overloading and class templates.

C++ Classes and Objects uses a simple box as an example of a class and objects.

Introduction to Classes in C++ is part of a course which attempts to explain the logic used in building classes and objects.

13. Classes and Objects in Physics

Guide to Scientific Computing in C++, written by Joe Pitt-Francis and Jonathan Whiteley, presents a very complete introduction to classes. The advantage of this text is that the concepts are explained for the practioners of scientific computing. The software developed in this book is available on-line at Book_material.

In particular, the authors show how to use a class to implement complex arithmetic in C++. The software is extracted in Complex_Arithmetics.tar.