Octet

Getting Started with C++

Abstract

This webpage has a collection of notes on the programming language C++. It follows along with Bjarn Stroustrup’s book Programming - Principles and Practice Using C++. The notes were taken for Microsoft Windows platforms. It hopes to be a starting point, and not a complete reference or tutorial, on the C++ programming language. It has chapters on:

  • Installing Visual C++ 2010 Express.
  • Command line samples using the compiler and linker.
  • Code samples.

It is targeted towards computer programmers who are new to C++. It is also targeted towards computer programmers who have used C++ before, but may be rusty.

Introduction

C++ is a general purpose programming language. It began development at Bell Labs in the late 1970s, and the first commercial release of it was in the mid 80s. It is a compiled language, and is very popular for games and high performance applications. It is:

  • Fast — since it can be compiled to machine code (or very fast intermediate code, e.g. managed code with the .NET framework) and can use low level machine operations.
  • Popular — being the language of choice for numerous projects from games to simulations.
  • Standardized — there is a C++ standard that officially documents how implementations of compilers, linkers, and other related software should perform.

It was developed initially by Bjarn Stroustrup.

History

There are many good articles on the history of the language. Some are listed here:

The last link is perhaps the most complete on the topic.

Installation

Setting up your environment to build C++ applications can be done on Windows, Mac, and Linux/Unix operating systems. For Visual Studio 2010 (or the latest) on Windows, it is fairly straight forward: just clicking 'next' several times through an installation wizard.

MinGW contains a port of the GNU Compiler Collection, which has a C++ compiler: MinGW. Linux users typically have g++ to work with, or can obtain it easily: How to start a C++ project in Linux/emacs environment. Mac users can get g++ as well: How to Install g++ on the Mac.


These notes are for Visual C++ 2010 Express, but they should not be much different for the other environments.

Background

In his book, Bjarn describes the process of developing a program as having four stages:

  • Analysis: What's the problem? What does the user want? What does the user need? What can the user afford? What kind of reliability do we need?
  • Design: How do we solve the problem? What should be the overall structure of the system? Which parts does it consist of? How do those parts communicate with each other? How does the system communicate with its users?
  • Programming: Express the solution to the problem (the design) in code. Write the code in a way that meets all constraints (time, space, money, reliability, and so on). Make sure that the code is correct and maintainable.
  • Testing: Make sure the system works correctly under all circumstances required by systematically trying it out.

He also mentions that the last two stages may be called implementation. He gives numerous reasons why programming is extremely important, and how ubiquitous it is, since computers are involved in billions of devices .

Command Line

There are several commands to get used to from the command line, as well as numerous command line parameters. A sample of some popular ones are listed as follows:


COMPILING
The C++ compiler translates C++ source code into what is called object code.
Object code files have an extension of .obj on Windows, and .o on Linux/Unix systems.

LINKING
Linking translates object code into machine executable code for a target machine.
It produces a .exe file on windows, and something like a .out file (or no extension) for Linux/Unix.

COMPILING AND LINKING
Visual Studio combines compiling and linking with cl.exe.

In the Visual Studio IDE, you can just hit 'build', and it will both compile and link your program.
You may also hit the green play arrow, and it will build the program, then launch it in a debugger.

From the command prompt, you can type:
	cl main.cpp
And it will compile main.cpp. You can also type something like:
	cl /EHsc basic.cpp
And it will compile with exception handling. You can compile both native C++
programs, and ones that use .NET classes. If you want to use .NET classes,

“You must use the /clr (Common Language Runtime Compilation) compiler option
because this program uses .NET classes and must include the required .NET libraries.
The Visual C++ compiler generates an .exe file that contains MSIL code instead
of machine executable instructions.”
MSDN Walkthrough: Compiling a Native C++ Program on the Command Line

Consult help files and documentation.

Code Samples

Sample #1: A Classic Hello World example

You may notice several variations on this example. Here is one that comes with the book (with minor changes).


#include "std_lib_facilities.h"

int main()
{
	// Output "Hello World!" to the screen.
	cout << "Hello World!";

	// Return 0 for success.
	return 0;
}

Other examples may start with #include <iostream> instead, or have std::cout, or have other variations. This has to do with the precompiler including different pieces of code, and the using statement, which will make more sense as you get to know the language. For now, it is enough to say this example will work, but you have to download st_lib_facilities.h from Bjarn’s website.

Sample #2: Reading from the command line

Example 1 writes to the command line, this one reads from it. Per Bjarn, the "c" stands for "character" because iostreams map values to and from byte (char) representations. Some terminology:

  • “An object is a region of memory with a type that specifies what kind of information can be placed into it.”
  • “A named object is called a variable.”
  • “You can think of an object as a ‘box’ into which you can put a value of the object’s type.”

Here is the actual example:


#include "std_lib_facilities.h"

int main()
{
	// Prompt the user for their name.
	cout << "Please enter your first name: ";

	// "This sets aside an area in memory for holding a string of characters
	// and gives it the name 'first_name'. A statement that introduces a new
	// name into a program and sets aside memory for a variable is called
	// a definition."
	string first_name;

	// Pronounced "See-in" first_name
	// Store the value provided by the user in the 'first_name' variable.
	// The first_name object is of the type 'string', so it is suited for storing
	// a string of characters.
	cin >> first_name;

	// Pronounced "See-cout" first_name
	cout << first_name;

	// Return 0 for success.
	return 0;
}

This sample has extra comments to point out some details. Normally there would be comments, but this might be too many for such a simple program. It is good to comment intentions, what you are trying to accomplish when you are writing the code. Some people will even write all their comments first before writing a single line of code. Many times each function will also have a large comment at the top, and each file, giving a summary of what is about to follow.

Sample #3: Reading other things from the command line

Nothing fancy here. This example demonstrates reading a string and an int from the command line.


#include "std_lib_facilities.h"

int main()
{
	cout << "Please enter your first name: " << endl;
	string first_name;
	cin >> first_name; // Read characters into name from the keyboard

	// Pronounced "See-cout" first_name
	cout << "Please enter your age: " << endl;
	int age;
	cin >> age;

	cout << "Hello " << age << " year old " << first_name;
	// Note: cin and cout are part of the standard input stream and output stream.
	// The >> operator means 'get from'.
	// It is sensitive to type.

	// Return 0 for success.
	return 0;
}

The newlines are what triggers the command line to send the typed characters to the user.

Sample #4: Common types and operators

Here is a table of common operators and types.

 boolcharintdoublestring
assignment = = = = =
addition     + +  
concatenation         +
subtraction     - -  
multiplication     * *  
division     / /  
remainder (modulo)     %    
increment by 1     ++ ++  
decrement by 1     -- --  
increment by b     +=n +=n  
add to end         +=
decrement by n     -= -=  
multiply and assign     *= *=  
divide and assign     /= /=  
remainder and assign     %=    
read from s into x s >> x s >> x s >> x s >> x s >> x
write x to s s << x s << x s << x s << x s << x
equals == == == == ==
not equal != != != != !=
greater than > > > > >
greater than or equal >= >= >= >= >=
less than < < < < <
less than or equal <= <= <= <= <=

Assignment gives a variable a new value. The operations are executed on the right hand side of this operator first. The value might be a memory address, or something more complex, as will be shown later on.

Sample #5: While loop

Looping is a key concept in most languages.


int main()
{
	int number_of_words = 0;
	string previous = " ";
	string current;

	while (cin >> current) {
		number_of_words++;
		if (previous == current) {
			cout << "repeated word: " << current << '\n';
		previous = current;
	}
}

Bjarn points out this code may be useful for grammar checkers. The number of words can be incremented with the ++ operator, or by typing += 1, or ++number_of_words. Each can mean slightly different things, but will result in the same result for this example. Semantic programming is another topic that may recommend ++number_of_words, because it is more in line with what you are trying to do. It may also perform better. Those kinds of discussions can be found all over the web.

Sample #6: Name rules

In C++ a name starts with a letter and contains only letters, digits, and underscores.


int main()
{
	string x;
	int number_of_statements;
	string X2;

	int 2x; // this will fail
	int $x; // this will fail
}

Other languages, notably JavaScript, allow the $ in the name.

Sample #7: More terminology

Here is more terminology from the book:

  • A type defines a set of possible values and a set of operations.
  • An object is some memory that holds a given type.
  • A value is a set of bits in memory interpreted according to a type.
  • A variable is named object.
  • A declaration is a statement that gives a name to an object.
  • A definition is a declaration that sets aside.

Knowing these terms are critical to understanding programs as they get more complex.

Review, Terms, and More

  1. “C++ is a programming language designed for a wide selection of programming tasks.”
  2. cout is pronounced “see-out”
  3. cout is an abbreviation for “character output stream.”
  4. Comments are written after the token //. Block comments are enclosed in /* */.
  5. A C++ compiler takes this source code, and compiles it into object code.
  6. std_facilities.h is a header file
  7. << is the output operator
  8. “Put a semi-colon after every expression that does not end with a right curly brace.”
  9. A library is code that we access using declarations found in an #included file.
  10. A declaration is a program statement specifying how a piece of code can be used.
  11. Errors can be classified as: compile-time errors, link-time errors, run-time errors or logic errors.
  12. The linker links the translation units (.o files) toghether.
  13. A function has four parts: A return type, a name, a parameter list, and a function body.
  14. The most minimal C++ program is int main( ){ }
  15. C++ is a compiled language. Meaning it has to be translated from human-readable to machine-readable.
  16. “A cursor is a blinking character or line showing where you can type the next character.”
  17. “A part of a C++ program that specifies an action and isn’t an #include directive (or some other preprocessor directive) is called a statement.”
  18. An object is a region of memory with a [type] that specifies what kind of information can be placed in it.
  19. A named object is called a [variable]. Character strings are put into string variables Integers are put into int variables.
  20. A prompt is a message that prompts the user to take an action.
  21. A statement that introduces a new name into a program and sets aside memory for a vairable is called a [definition].
  22. Double is a legacy term for "double-precision floating-point" numbers
  23. Initialization is giving a variable its initial value; assignment is giving a variable a new value.
  24. In C++ a name starts with a letter and contains only letters, digits, and underscores.
  25. There are safe ways to convert. char-to-int conversion is safe. There are also unsafe conversions. For example, int to char for large ints. This is called a narrowing conversion.
  26. Methods of sharing data include main memory, persistent storage devices, and over networks.
  27. Parts of a program are things like functions.
  28. Input and output could mean data coming into and out of the computer, or info produced by another program.
  29. Inputs are often called arguments.
  30. Outputs are often called results.
  31. Computation is the act of producing some outputs based on inputs.
  32. Computers used to be defined as a person who did some computations.
  33. Our job as programmers is to express computations correctly, simply, and efficiently.
  34. We use abstraction as well as divide and conquer techniques.
  35. Rather than accessing memory directly, we access it through typed and named variables, but it can be accessed directly as well.
  36. Divide and conquer might mean read the data, sort the data, print the data for a dictionary.
  37. The iostreams save us from having to directly deal with the hardware's input/output ports. This is an example of using abstraction.
  38. A constant is a named object to which you can't give a new value (const double pi = 3.14159;) (299792458 // speed of light in meters per second measured in a vacuume)
  39. lval: short for the value that can appear on the left-hand side of an operation.
  40. = is an operation so a=b is an expression and we need the terminating semi-color a=b; to make it a statement.
  41. An empty statement is a blank line followed by a semi-colon.
  42. There are noviced, intermediate, and expert programmers.
  43. Selection, or selecting among alternatives, is accomplished with if statements.
  44. To switch based on a string you have to use an if-statement or a map.
  45. The first stored program was run on May 6, 1949 in Cambridge University, the EDSAC.
  46. void means "nothing" as the return type.
  47. The caller deals with errors in most cases. The callee doesn't have all the information. Check your arguments in a function unless you have a good reason not to.
  48. A token is a sequence of characters that represents something we consider a unit.
  49. A header is a collection of declarations.
  50. You can pass by reference, or pass by const reference.
  51. C++ has two kinds of user defined types: classes and enumerations. A struct is a class where the memers are public by default. There are no private implementation details for a struct. A struct is good for something that just has data.

Sample switch
case 'i': case '3': case '5':
	cout << length << "...
	break;
..
default:

	break;

}

Sample xor swap:
 void xorSwap (int *x, int *y) {
     if (x != y) {
         *x ^= *y;
         *y ^= *x;
         *x ^= *y;
     }
 }

// Example of how to set a constant for a complex type.
// A static local variable is used because it is initialized only the first time it is called.
// A reference is returned to prevent any unnecessary copying.
// A const reference is returned to prevent the value from being accidentally changed.

const Date& default_date()
{
	static const Date dd(1970,1,1);
	return dd;
}


Struct example
struct Date {
	int y, m, d;
	Date(int y, int m, int d);
	void add_day(int n);
};

enum Month {
	jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
};

Operator example
int operator+(int,int);
Vector operation+(const Vector&, const Vector&);

Jumping ahead, here is a sample from a beginner program that deals with flooding. There is still a lot to learn about C++, follow along with tutorials online, or Bjarn’s book!


FloodModel.h

#ifndef FLOOD_MODEL
#define FLOOD_MODEL


#include "MatrixIO.h"
#include "SimpleFile.h"
#include <queue>

struct Coordinate {
	int row;
	int col;
	Coordinate(int r, int c) : row(r), col(c) {}
};

class FloodCell {
public:
	unsigned short currentAltitude;
	unsigned short initialAltitude;
	bool isFlooded;
	bool isQueued; // queued to be flooded more
};
class FloodModel {
public:
	double startAltitude;
	double nextAltitude;	// altitude of next heighest neighbor
	double currAltitude; // current altitude of the cell being flooded
	double deltaAltitude;
	double newAltitude; // typically currAltitude + deltaAltitude OR nextAltitude

	int inputRow;
	int inputCol;

	FloodModel( )
		: nextAltitude(2.0),
		currAltitude(2.0),
		deltaAltitude(2.0),
		newAltitude(2.0)
	{
		floodNextPtr = new queue<Coordinate>( );
	}
	~FloodModel( ) { }

	void loadCells(string filepath, int numRows, int numCols, int inputRow, int inputCol, SimInput s);
	void writeToBMP(string filepath, SimInput s);

	void step( );
private:
	typedef Numeric_lib::Matrix<FloodCell,2>* CellSpacePtr;
	typedef Numeric_lib::Matrix<FloodCell,2> CellSpace;
	//typedef Numeric_lib::Matrix<bool,2>* Flagged;

	// Initial terrain
	CellSpacePtr cellSpacePtr;

	// Flooded terrain
	//CellSpacePtr cellSpacePtrFlood;

	// Flagged terrain (to be flooded next)
	//Flagged cellSpacePtrFlagged;


	// Keep a list of which ones need to be flooded next
	queue<Coordinate>* floodNextPtr;

	void queueNeighbors(int row,int col);
};
#endif

FloodModel.cpp - just the loadCells function

void FloodModel::loadCells(string filepath, int numRows, int numCols, int inputRow, int inputCol, SimInput s) {
	std::cout << "Loading matrix at " << filepath << " that is " << numRows << " by " << numCols << " with input row " << inputRow << " and input column " <<  inputCol << endl;
	this->inputRow = inputRow;
	this->inputCol = inputCol;
	startAltitude = s.startElevation;

	vector<double> data;
	SimpleFile sf;
	sf.file_to_vector( filepath, data );
	//data = sf.stream_file_to_vector( filepath.c_str() );

	cellSpacePtr = new CellSpace(numRows,numCols);

	double min = 10000, max = 0, value = 0;
	for (int row = 0; row < cellSpacePtr->dim1(); ++row){
		for (int col = 0; col < cellSpacePtr->dim2(); ++col) {
			value = data[row*cellSpacePtr->dim2()+col];
			if (value >= 0) {
				(*cellSpacePtr)[row][col].initialAltitude = value;
				(*cellSpacePtr)[row][col].currentAltitude = value;
				(*cellSpacePtr)[row][col].isFlooded = false;
				(*cellSpacePtr)[row][col].isQueued = false;

				if (value < min) {
					min = value;
					//cout << "New min: " << min;
				}
				if (value > max) {
					max = value;
					//cout << "New max: " << max;
				}
			} else {
				(*cellSpacePtr)[row][col].initialAltitude = 0;
				(*cellSpacePtr)[row][col].currentAltitude = 0;
				(*cellSpacePtr)[row][col].isFlooded = true;
				(*cellSpacePtr)[row][col].isQueued = false;
			}
		}// end for
		if ((row % 10) == 0) {
				std::cout << "The program has finished loading row " << row << " of the matrix." << endl;
		}
	}

	filepath += ".bmp";
	std::cout << "Writing bitmap to " << filepath << endl;

	writeToBMP(filepath, s);

	std::cout << "Finished loading matrix." << endl;
}




This code uses Bjarn’s matrix class. His matrix class is available online on his samples page. About the sample:


“typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to form complex types from more-basic machine types and assign simpler names to such combinations.”

Typedef on Wikipedia

The above example uses the scope operator (::, two colons) to define a member of a class outside the class definition. This is helpful because the class definition can be in the .h header file, but the implementation in a separate file.


Constructors and destructors are used. A user defined type FloodModel is created. Pointers are used. The members of an object can be accessed directly using an arrow operator ->


Struct is just like class, but members have public access by default rather than private. There are also unions, which are like classes and structs. See a C++ Tutorial on classes.


C++ also offers inheritance. See for example Tutorials Point: C++ Inheritance. This introduces the protected keyword for access.


Pointers and arrays are key concepts. See a good tutorial on pointers. This tutorial even covers pointers to function.

References

This is the supporting material page for the book:

[1] Programming — Principles and Practice Using C++ Support Page
http://www.stroustrup.com/Programming/

Return to Octet