Optionally, these parentheses may enclose a list of parameters within ... a sequence of characters (in this case the Hello World sequence of ..... stored until this moment in a is not considered at all in this operation, and in fact that value is lost.
cplusplus.com
C++ Language Tutorial
Written by: Juan Soulié Last revision: June, 2007
Available online at:
http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain corrections and changes
The C++ Language Tutorial
This document and its content is copyright of cplusplus.com © cplusplus.com, 2008. All rights reserved. Any redistribution or reproduction of part or all of the content in any form is prohibited other than to print a personal copy of the entire document or download it to a local hard disk, without modifying its content in any way (including, but not limited to, this copyright notice). You may not, except with express written permission from cplusplus.com, distribute the content of this document. Nor may you transmit it or store it in any other website or other form of electronic retrieval system. 2
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
Table of contents Table of contents ...............................................................................................................................3 Introduction ......................................................................................................................................5 Instructions for use ................................................................................................................................... 5 Basics of C++ ......................................................................................................................................7 Structure of a program ............................................................................................................................. 7 Variables. Data Types. ............................................................................................................................. 11 Constants ................................................................................................................................................ 17 Operators ................................................................................................................................................ 21 Basic Input/Output.................................................................................................................................. 29 Control Structures ............................................................................................................................ 34 Control Structures ................................................................................................................................... 34 Functions (I) ............................................................................................................................................ 41 Functions (II) ........................................................................................................................................... 47 Compound data types ...................................................................................................................... 54 Arrays ...................................................................................................................................................... 54 Character Sequences .............................................................................................................................. 60 Pointers ................................................................................................................................................... 63 Dynamic Memory.................................................................................................................................... 74 Data structures........................................................................................................................................ 77 Other Data Types .................................................................................................................................... 82 Object Oriented Programming.......................................................................................................... 86 Classes (I)................................................................................................................................................. 86 Classes (II) ............................................................................................................................................... 95 Friendship and inheritance ................................................................................................................... 100 Polymorphism ....................................................................................................................................... 107 Advanced concepts ........................................................................................................................ 113 Templates.............................................................................................................................................. 113 Namespaces .......................................................................................................................................... 120 Exceptions ............................................................................................................................................. 123 Type Casting .......................................................................................................................................... 127
3
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
Preprocessor directives......................................................................................................................... 133 C++ Standard Library ...................................................................................................................... 138 Input/Output with files ......................................................................................................................... 138
4
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
Introduction
Instructions for use To whom is this tutorial directed? This tutorial is for those people who want to learn programming in C++ and do not necessarily have any previous knowledge of other programming languages. Of course any knowledge of other programming languages or any general computer skill can be useful to better understand this tutorial, although it is not essential. It is also suitable for those who need a little update on the new features the language has acquired from the latest standards. If you are familiar with the C language, you can take the first 3 parts of this tutorial as a review of concepts, since they mainly explain the C part of C++. There are slight differences in the C++ syntax for some C features, so I recommend you its reading anyway. The 4th part describes object-oriented programming. The 5th part mostly describes the new features introduced by ANSI-C++ standard.
Structure of this tutorial The tutorial is divided in 6 parts and each part is divided on its turn into different sections covering a topic each one. You can access any section directly from the section index available on the left side bar, or begin the tutorial from any point and follow the links at the bottom of each section. Many sections include examples that describe the use of the newly acquired knowledge in the chapter. It is recommended to read these examples and to be able to understand each of the code lines that constitute it before passing to the next chapter. A good way to gain experience with a programming language is by modifying and adding new functionalities on your own to the example programs that you fully understand. Don't be scared to modify the examples provided with this tutorial, that's the way to learn!
Compatibility Notes The ANSI-C++ standard acceptation as an international standard is relatively recent. It was first published in November 1997, and revised in 2003. Nevertheless, the C++ language exists from a long time before (1980s). Therefore there are many compilers which do not support all the new capabilities included in ANSI-C++, especially those released prior to the publication of the standard. This tutorial is thought to be followed with modern compilers that support -at least on some degree- ANSI-C++ specifications. I encourage you to get one if yours is not adapted. There are many options, both commercial and free.
Compilers The examples included in this tutorial are all console programs. That means they use text to communicate with the user and to show their results.
5
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
All C++ compilers support the compilation of console programs. Check the user's manual of your compiler for more info on how to compile them.
6
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
Basics of C++
Structure of a program Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program: // my first program in C++ Hello World! #include using namespace std; int main () { cout b ? a : b
// // // //
returns returns returns returns
3, since 7 is not equal to 5. 4, since 7 is equal to 5+2. the value of a, since 5 is greater than 3. whichever is greater, a or b.
// conditional operator
7
#include using namespace std; int main () { int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7.
Comma operator ( , ) The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. For example, the following code: a = (b=3, b+2);
25
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.
Bitwise Operators ( &, |, ^, ~, ) Bitwise operators modify variables considering the bit patterns that represent the values they store. operator asm equivalent description & AND Bitwise AND | OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary complement (bit inversion) > SHR Shift Right
Explicit type casting operator Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()): int i; float f = 3.14; i = (int) f; The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses: i = int ( f ); Both ways of type casting are valid in C++.
sizeof() This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution.
Other operators Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming. Each one is treated in its respective section.
Precedence of operators When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: a = 5 + 7 % 2
26
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
we may doubt if it really means: a = 5 + (7 % 2) a = (5 + 7) % 2
// with a result of 6, or // with a result of 0
The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows: Level 1 2
Operator
Description
::
scope
() [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid ++ -- ~ ! sizeof new delete
postfix
+ -
unary (prefix) indirection and reference (pointers) unary sign operator
4
(type)
type casting
5
.* ->*
pointer-to-member
6
* / %
multiplicative
7
+ -
additive
8
>
shift
9
< > =
relational
10
== !=
equality
11
&
bitwise AND
12
^
bitwise XOR
13
|
bitwise OR
14
&&
logical AND
15
||
logical OR
16
?:
conditional
17
= *= /= %= += -= >>= 0; n--) { cout yourname; cout set_values (4,5); ppoly2->set_values (4,5); cout area() printarea(); ppoly2->printarea(); return 0; } Virtual members and abstract classes grant C++ the polymorphic characteristics that make object-oriented programming such a useful instrument in big projects. Of course, we have seen very simple uses of these features, but these features can be applied to arrays of objects or dynamically allocated objects. Let's end with the same example again, but this time with objects that are dynamically allocated:
111
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
// dynamic allocation and polymorphism #include using namespace std;
20 10
class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout area() set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); delete ppoly1; delete ppoly2; return 0; } Notice that the ppoly pointers: CPolygon * ppoly1 = new CRectangle; CPolygon * ppoly2 = new CTriangle; are declared being of type pointer to CPolygon but the objects dynamically allocated have been declared having the derived class type directly.
112
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
Advanced concepts
Templates Function templates Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function. These function templates can use these parameters as if they were any other regular type. The format for declaring function templates with type parameters is: template function_declaration; template function_declaration; The only difference between both prototypes is the use of either the keyword class or the keyword typename. Its use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way. For example, to create a template function that returns the greater one of two objects we could use: template myType GetMax (myType a, myType b) { return (a>b?a:b); } Here we have created a template function with myType as its template parameter. This template parameter represents a type that has not yet been specified, but that can be used in the template function as if it were a regular type. As you can see, the function template GetMax returns the greater of two parameters of this stillundefined type. To use this function template we use the following format for the function call: function_name (parameters); For example, to call GetMax to compare two integer values of type int we can write: int x,y; GetMax (x,y); When the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appearance of myType by the type passed as the actual template parameter (int in this case) and then calls it. This process is automatically performed by the compiler and is invisible to the programmer. Here is the entire example:
113
© cplusplus.com 2008. All rights reserved
The C++ Language Tutorial
// function template #include using namespace std;
6 10
template T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout