Language:EN
Pages: 144
Rating : ⭐⭐⭐⭐⭐
Price: $10.99
Page 1 Preview
and has exactly the same meaning int integer data

And has exactly the same meaning int integer data types char

cplusplus.com
C++ Language Tutorial

Written by: Juan Soulié

http://www.cplusplus.com/doc/tutorial/

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

This document and its content is copyright of cplusplus.com © cplusplus.com, 2008. All rights reserved.

2 © cplusplus.com 2008. All rights reserved

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

4 © cplusplus.com 2008. All rights reserved

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

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.

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!

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

6 © cplusplus.com 2008. All rights reserved

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

Basics of C++

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

Hello World!

using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes included in these tutorials.

int main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it - the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.

7 © cplusplus.com 2008. All rights reserved

cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually produce some effect. In fact, this statement performs the only action that generates a visible effect in our first program.

cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output stream (which usually is the screen).

The program has been structured in different lines in order to be more readable, but in C++, we do not have strict rules on how to separate instructions in different lines. For example, instead of

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

Let us add an additional instruction to our first program:

8 © cplusplus.com 2008. All rights reserved

Hello World! I'm a C++ program

In this case, we performed two insertions into cout in two different statements. Once again, the separation in different lines of code has been done just to give greater readability to the program, since main could have been perfectly valid defined this way:

Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They are lines read and processed by the preprocessor and do not produce any code by themselves. Preprocessor directives must be specified in their own line and do not have to end with a semicolon (;).

Comments

We are going to add comments to our second program:

9 © cplusplus.com 2008. All rights reserved

cout << "I'm a C++ program"; // prints I'm a C++ program
return 0;
}

Hello World! I'm a C++ program

10 © cplusplus.com 2008. All rights reserved

The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting program just to obtain a simple sentence written on the screen as result. It certainly would have been much faster to type the output sentence by ourselves.

However, programming is not limited only to printing simple texts on the screen. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work we need to introduce the concept of variable.

Obviously, this is a very simple example since we have only used two small integer values, but consider that your computer can store millions of numbers like these at the same time and conduct sophisticated mathematical operations with them.

Therefore, we can define a variable as a portion of memory to store a determined value.

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved words under some circumstances:

11 © cplusplus.com 2008. All rights reserved

Very important: The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers.

Fundamental data types

Name Description Size* Range*

Character or small integer.

1byte

signed: -128 to 127 unsigned: 0 to 255

int

Integer.

long int (long)

signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295

bool

Floating point number.

4bytes

+/- 1.7e +/- 308 (~15 digits)

long double

Wide character.

2 or 4 bytes

1 wide character

12 © cplusplus.com 2008. All rights reserved

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:

unsignedshortint NumberOfSisters;

By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written:

short Year;

shortint Year;

13 © cplusplus.com 2008. All rights reserved

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

// print out the result: cout << result;

// terminate the program: return 0;
}

A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.

Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

14 © cplusplus.com 2008. All rights reserved

When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized:

type identifier (initial_value) ;

For example:

int main ()
{
int a=5; // initial value = 5 int b(2); // initial value = 2 int result; // initial value undetermined

a = a + 3;
result = a - b;
cout << result;

15 © cplusplus.com 2008. All rights reserved

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

int main ()
{
string mystring = "This is a string"; cout << mystring;
return 0;
}

This is a string

// my first string
#include <iostream>
#include <string>
usingnamespace std;

int main ()
{
string mystring;
mystring = "This is the initial string content"; cout << mystring << endl;
mystring = "This is a different string content"; cout << mystring << endl;
return 0;
}

16 © cplusplus.com 2008. All rights reserved

Constants

Constants are expressions with a fixed value.

a = 5;

the 5 in this piece of code was a literal constant.

In addition to decimal numbers (those that all of us are used to use every day) C++ allows the use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to precede it with a 0 (zero character). And in order to express a hexadecimal number we have to precede it with the characters 0x (zero, x). For example, the following literal constants are all equivalent to each other:

75 // decimal 0113 // octal

75ul // unsigned long

In both cases, the suffix can be specified using either upper or lowercase letters.

17 © cplusplus.com 2008. All rights reserved

TThheeCC++++LLaanngguuaaggeeTTuuttoorriiaall

Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings.

Character and string literals

x
'x'

x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.

18 © cplusplus.com 2008. All rights reserved
\n newline
\r carriage return
\v vertical tab
\b backspace

\f form feed (page feed)

\a
\a alert (beep)
\' \' single quote (')
\" \" double quote (")
\? \? question mark (?)
\\ \\ backslash (\)

For example:

(hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A).

String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each

newline or any other valid blank character:

"this forms""a single""string""of characters"

Finally, if we want the string literal to be explicitly made of wide characters (wchar_t), instead of narrow characters

L"This is a wide character string"

Defined constants (#define)
You can define your own names for constants that you use very often without having to resort to memory-

consuming variables, simply by using the #define preprocessor directive. Its format is:

19 © cplusplus.com 2008. All rights reserved

#define PI 3.14159

#define NEWLINE '\n'

// defined constants: calculate circumference #include <iostream>
usingnamespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}

The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces.

Declared constants (const)

Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

20 © cplusplus.com 2008. All rights reserved

You are viewing 1/3rd of the document.Purchase the document to get full access instantly

Immediately available after payment
Both online and downloadable
No strings attached
How It Works
Login account
Login Your Account
Place in cart
Add to Cart
send in the money
Make payment
Document download
Download File
img

Uploaded by : Joe White

PageId: DOC676CBC7