C++ Programming
by examples


Appendix Purpose and Scope

This Appendix to the C++ Programming book will attempt to provide users a complementary practical understanding of the C++ programming language. It will be an aggregation dependent on the lessons and theoretical content already presented on the C++ Programming book, so to consistently list all compilable example programs that are used in the main book, this appendix will be useful to refresh your knowledge in a hands-on approach, guarantee performance and permit easier maintenance of the used code and test derivations of the examples used.

This is an open work, if you find any problems with terms or concepts you can help by contribute to it, your participation is needed and welcomed! You are also welcome to state any preference, shortcomings or vision for the actual book content, structure or other conceptual matters, see this Wikibook's discussion page for the right forum for participating.

Referencing the learning chapters
If you have questions related to C++ that are not addressed on the book, ask at the Q&A or check
Subject:C++ programming language

Preamble

C++ Programming by examples can be used as an alternative approach to learn the language, by putting practice over theory. In any case this will require you to have greater level of expertise. You will need to understand how C++ files are organized, have and know how to operate a compiler and understand some nuances that will not be visible in code. Do understand that you will be able to read and program in C++, to some degree but to get to really understand the language, theory, not only practice, is required. Use the primary book as a reference anytime you have a doubt.

In the book we cover where to get a compiler (see the Compiler Section), this will provide you the tool needed to proceed. If you don't have, want or need a compiler installed on you machine you can use a WEB free compiler available at http://ideone.com (or http://codepad.org but you will have to change the code not to require interactive input).

Chapter 1: C++ a multi-paradigm language


This is the initial chapter of the book, it attempts to introduce the C++ language to the reader, speak of the language history and its evolution. providing an overview in an attempt to convey the reasons why one should come to know the language.
To understand C++, first one must establish what a programming language is, how they relate with each other (Low-level/High-level), the different programming paradigms, the Procedural programming and Object-oriented programming (Objects and Classes, Encapsulation, Inheritance, Multiple inheritance, Polymorphism), Generic programming, etc. As a way to permit to, not only to provide some useful background, but for readers with experience in other languages to understand how particular C++ is as compared to the other languages that are closely related, C (the origin of C++), Java, C#, (C++/CLI) and D.
In this chapter readers are asked to examine the first C++ source code, the common Hello World and provided the resources to understand it in step-by-step way.

Hello World - Writing, Compiling and Running a C++ Program

Below is an example of a simple C++ program:

// 'Hello World!' program 
 
#include <iostream>
 
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}


When you write a program, you use a development environment. Your development environment can be a basic text editor or a feature rich C++ integrated development environment (IDE). You should not use a word processor like Microsoft Word, because it adds formatting codes to the text.

If a compiler is not already available to you, see the Where to get a compiler Section of the book.

Open your development environment and type the program shown (or copy and paste it) and save it as hello.cc.

Now compile it using the C++ compiler:

COMMAND_PROMPT> g++ hello.cc -o hello

The example uses GCC, the GNU Compiler Collection ( http://gcc.gnu.org ) but you could use any other compiler, or use an IDE to compile it. The above command would produce an executable called hello or hello.exe. Invoke the executable to run your first C++ program:

Unix:

COMMAND_PROMPT> ./hello
Hello World!
COMMAND_PROMPT>

Microsoft Windows:

COMMAND_PROMPT> dear hello
Hello World!
COMMAND_PROMPT>

Text that is italicized is typed by you and the bold text is output by the program. If you use an IDE, it might automatically color the code for you based on the syntax.

Troubleshooting

g++
command not found

You don't have the GNU C++ compiler installed. If you have a different compiler, check its documentation for the correct compilation command.

Note:
There is detailed information on how to get a compiler and how to install it on the Where to get a compiler Section.
In Appendix B:External References you will also find references to other freely available compilers and even full IDEs you can use.

Wrong Compiler Command

Lot of weird errors, mentioning many times:

undefined reference to `std::basic_ostream' [..]

Usually ending with:

collect2: ld returned 1 exit status

To use g++ to compile your hello.cc, use:

g++ hello.cc -o hello

For gcc, use:

gcc hello.cc -o hello -lstdc++

Note:
For simplicity, we assume that the file is in the path you are using...

hello
command not found

You did not type the full path, try:

./hello

Is there a hello program in this directory? Can you see it when you type ls? If not, your compilation (g++ hello.cc -o hello) failed or you have changed to a wrong directory.

If you do not specify -o hello, g++ names the output file a.out (assembler output) for historical reasons. In such a case, type:

./a.out

to execute the program.

Your First C++ Program Explained

The preprocessing directive

Some features of C++ are part of the language and some others are part of a standard library. The standard library is a body of code that is available with every C++ compiler that is standards compliant. When the C++ compiler compiles your program it usually also links it with the standard C++ library.

When you use features from the library, C++ requires you to declare the features you will be using. The first line in the program is a preprocessing directive. In our example it is shown bold and italicized:

The preprocessing Directive for IOStreams
 #include <iostream>

This line causes the C++ declarations which are in the iostream header to be included for use in your program. Usually the compiler inserts the contents of a header file called iostream into the program. Where it puts it depends on the system. The location of such files may be described in your compiler's documentation. A list of standard C++ header files is in the standard headers reference tables.

The iostream header contains various declarations for input/output (I/O). It uses an abstraction of I/O mechanisms called streams. For example there is an output stream object called std::cout which is used to output text to the standard output. Usually, this displays the text on the computer screen.

The preprocessor is a part of the compiler which does some transformations to your code before the actual compiler sees it. For example, on encountering a #include <iostream> directive, it replaces the directive with the contents of the iostream header file.

main Function

int main()
{
    // ...
}

The lines above represent a block of C++ code, given the name main. Such a named block of code is called a function in C++ parlance. The contents of the block are called the body of the function.

The word int is shown in bold because it is a keyword. C++ keywords have some special meaning and are also reserved words, i.e., cannot be used for any purpose other than what they are meant for. On the other hand main is not a keyword and you can use it in many places where a keyword cannot be used (though that is not recommended, as confusion could result).

Every (standards-compliant) C++ program must define a function called main. This is where the execution of the program begins. As we shall see later, main may call other functions which may call yet other functions. The compiler arranges for main function to be called when the program begins executing. (Although this is generally true, it is not always true. There is an exception to main's being executed at the very beginning that we will see later.)

Now let us look at the code inside the main function.

Printing Hello World!

The first line in main uses the std::cout object to print the string (sequence of characters) Hello World! and end the line:

std::cout << "Hello World!\n";

This line is a C++ statement. C++ statements are terminated by a semicolon (;). Within the statement <<, called the insertion operator is used to output the string using the std::cout stream. C++ strings are enclosed within double quotes ("). The quotes themselves are not part of the string and hence not printed. The sequence \n is used within a string to indicate the end of the current line. Though the sequence is represented by two characters, it takes up only one character's worth of memory space. Hence the sequence \n is called the newline character. The actual procedure to start a new line is system-dependent but that is handled by the C++ standard library transparent to you.

Note:
C Programmers should not confuse the insertion operator with the bitwise shift operator in C. C++ has a feature called operator overloading which allows the two interpretations of << to coexist. In C++, I/O is the primary use of << and >>, and bit shifting is a relatively uncommon use.

Modifications to the Above Program

Here is the same program with minor modifications:

// This program just displays a string and exits
#include <iostream>
 
int main()
{
  std::cout << "Hello World!";
  std::cout << std::endl;

  return 0;
}

Comments

The line added at the beginning:

// This program just displays a string and exits

is a comment that tries to explain what the code does. Comments are essential to any non-trivial program so a person who is reading the code can understand what it is expected to do. There is no restriction to what is contained between the comment delimiters. The compiler just ignores all that is there in the comment. Comments are shown italicized in our examples. C++ supports two forms of comments:

  • Single line comments start with a // and extend up to the end of the line. These can also be used to the right of statements to explain what that statement does.
  • Multi-line comments start with a /* sequence and end with a */ sequence. These can be used for comments spanning multiple lines. These are also known as C-style comments as this was the only type of comment originally available in C. e.g.:
/* This program displays a string
   and then it exits */

Comments are also used at times to enclose code that we temporarily want the compiler to ignore, but intend to use later. This is useful in debugging, the process of finding out bugs, or errors in the program. If a program does not give the intended result, by "commenting out" code, it might be possible to track which particular statement has a bug. As C-style comments can stop before the end of the line, these can be used to "comment out" a small portion of code within a line in the program.

Flushing the Output Stream Buffer

Whenever you write (i.e., send any output) to an output stream, it does not immediately get written. It is first stored in memory and may actually get written any time in the future. This process is called buffering and the regions in memory used for storing temporary data like this are called buffers. It is at times desirable to flush the output stream buffers to ensure all data has been written. This is achieved by applying the insertion operator to an output stream and the object std::endl. This is what is done by the line:

std::cout << std::endl;

Before flushing the buffer, std:endl also writes a newline character (which explains its name, end line). Hence the newline is omitted in the string printed in the previous line.

Returning Success Code

In most operating systems, every program is allowed to communicate to the invoker whether it finished execution successfully using a value called the exit status. As a convention, an exit status of 0 stands for success and any other value indicates failure. Different values for the exit status could be used to indicate different types of failures. In our simple program, we would like to exit with status 0.

C++ allows the main function to return an integer value, which is passed to the operating system as the exit status of the program. The statement:

return 0;

makes main to return the value 0. Since the main function is required to return an integer, the keyword int is used to begin the function definition. This statement is optional since the compiler automatically generates code to return 0 for the main function for the cases where control falls off without a return statement. This is why the first program worked without any return statements. Note that this is only a special case that applies only to the main function. For other functions you must return a value if they are declared to return anything.

Common Programming Error 1 Though the return statement is optional, main should not be declared to return void (a function declared as void is a function which does not return anything) as in some other languages like Java. Some C++ compilers may not complain about this, but it is wrong. Doing this could be equivalent to returning just about any random number that happened to be stored in a particular memory location or register, depending on the platform. This practice can also be potentially damaging to some operating systems, which rely on the return code to determine how to handle a crash or other abnormal exit.

Whitespace and Indentation

Spaces, tabs and newlines (line breaks) are usually called whitespace. These are ignored by the compiler except within quotes, apart from the rule that preprocessing directives and C++-style comments end at a newline. So the above program could as well be written as follows:

// This program just displays a string and exits, variation 1
#include <iostream>

int main() { std::cout<<"Hello World!"; std::cout<<std::endl; return 0; }

Note, however, that spaces are required to separate adjacent words and numbers. To make the program more readable, whitespace must be used appropriately.

The conventions followed when using whitespace to improve the readability of code constitute an Indent style. For example, with alternate indent styles, the program could be written like this:

// This program just displays a string and exits, variation 2
#include <iostream>
 
int main() {
  std::cout << "Hello World!";
  std::cout << std::endl;

  return 0;
}

or like this:

// This program just displays a string and exits
#include <iostream>
 
int main()
{
  std::cout << "Hello World!";
  std::cout << std::endl;

  return 0;
}

Chapter 1: Compilable examples

Hello World - Displays a string - Displays a string1 - Displays a string2

Chapter 2: Fundamentals for getting started



Data and Variables

Variables

Adds two numbers and prints their sum

// This program adds two numbers and prints their sum.
#include <iostream>
 
int main()
{
  int a;
  int b;
  int sum;

  sum = a + b;
 
  std::cout << "The sum of " << a << " and " << b << " is " << sum << "\n";
 
  return 0;
}

// This program adds two numbers and prints their sum, variation 1
#include <iostream>
#include <ostream>

using namespace std;

int main()
{
  int a = 123, b (456), sum = a + b;
 
  cout << "The sum of " << a << " and " << b << " is " << sum << endl;
 
  return 0;
}

One of the concepts for novice programmers is understanding how to write a program that sorts three integers. This comes in handy if you want to apply this to a program that you will later want to incorporate in a real-life situation. I am using this code to show how this can be applied for the purposes of using this code at work.

One example that comes to mind is if you were counting people such as (1) population density of a region or (2) the number of employees to get the demographics. For example, if you worked at the Census Bureau, and you wanted to measure how much of the population had moved from the Country to the City, you may way to sort the numbers. If you want to know if more women than men applied for a certain job, you will want to sort these the integers. Sometimes these types of Sorting functions can be seen on websites that filter and give the view with the largest integer descending down to the smallest of integers. Behind this User-interface (UI) is a Sorting function that is called when the User clicks a Submit button on a website.

This example takes 3 integers (from the User's Input) and sorts it. The main purpose of this section is to show how simple code can be used in real-life situations.

#include <iostream>
#include <cmath>

using namespace std;
void sortNums(int& input1, int& input2, int& input3);

int main()
{
	int x, y, z; // create variables

	// Get numbers using cout and cin
	cout << "Please enter 3 numbers." << endl;
	cin >> x;
	cin >> y;
	cin >> z;

	// Sort numbers: x, y, and z
	sortNums(x, y, z); // calls the function titled sortNums

	cout << x << ", " << y << ", " << z << endl; // outputs the numbers

	return 0;
}

void sortNums(int &myNumA, int &myNumB, int &myNumC) // sort numbers
{
	int temp; // create temp variable

	if (myNumA > myNumB)
	{
		temp = myNumA;
		myNumA = myNumB;
		myNumB = temp;
	}

	if (myNumB > myNumC)
	{
		temp = myNumB;
		myNumB = myNumC;
		myNumC = temp;
	}

	if (myNumA > myNumB)
	{
		temp = myNumA;
		myNumA = myNumB;
		myNumB = temp;
	}
}

Chapter 3: Object-Oriented Programming



Chapter 4: Advanced Features



Chapter 5: Beyond the Standard



Using a Class

// very simple C++ program using a class.

#include <iostream>

class myClass
{
public:
 myClass(int);

private:
 int i;
};

myClass::myClass(int x) : i(x) {}

int main()
{
  myClass my_class(5);

  // dynamic
  myClass* my_class_ptr = new myClass(5);
  delete my_class_ptr;

  return 0;
}

I/O Streams

// This program just displays a string and exits
#include <iostream>
 
int main()
{
  std::cout << "Hello World!";
  std::cout << std::endl;

  return 0;
}

// This program just displays a string and exits, variation 1
#include <iostream>

int main() { std::cout<<"Hello World!"; std::cout<<std::endl; return 0; }

// This program just displays a string and exits, variation 2
#include <iostream>
 
int main() {
  std::cout << "Hello World!";
  std::cout << std::endl;

  return 0;
}