Sign in or 

| Version | User | Scope of changes |
|---|---|---|
| Mar 12 2007, 6:11 AM EDT (current) | Anonymous | 43086 words added |
| Mar 12 2007, 6:08 AM EDT | Anonymous |
| Instructions for use | |
| // my first program in C++#include <iostream>using namespace std;int main (){ cout << "Hello World!"; return 0;} | Hello World! |
| int main (){ cout << " Hello World "; return 0;} |
| int main () { cout << "Hello World"; return 0; } |
| // my second program in C++#include <iostream>using namespace std;int main (){ cout << "Hello World! "; cout << "I'm a C++ program"; return 0;} | Hello World! I'm a C++ program |
| int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; } |
| int main (){ cout << "Hello World!"; cout << "I'm a C++ program"; return 0;} |
| // line comment/* block comment */ |
| /* my second program in C++ with more comments */#include <iostream>using namespace std;int main (){ cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0;} | Hello World! I'm a C++ program |
| a = 5;b = 2;a = a + 1;result = a - b; |
| Name | Description | Size* | Range* |
| char | Character or small integer. | 1byte | signed: -128 to 127 unsigned: 0 to 255 |
| short int (short) | Short Integer. | 2bytes | signed: -32768 to 32767 unsigned: 0 to 65535 |
| int | Integer. | 4bytes | signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 |
| long int (long) | Long integer. | 4bytes | signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 |
| bool | Boolean value. It can take one of two values: true or false. | 1byte | true or false |
| float | Floating point number. | 4bytes | 3.4e +/- 38 (7 digits) |
| double | Double precision floating point number. | 8bytes | 1.7e +/- 308 (15 digits) |
| long double | Long double precision floating point number. | 8bytes | 1.7e +/- 308 (15 digits) |
| wchar_t | Wide character. | 2bytes | 1 wide character |
| int a;float mynumber; |
| int a, b, c; |
| int a;int b;int c; |
| unsigned short int NumberOfSisters;signed int MyAccountBalance; |
| int MyAccountBalance; |
| short Year;short int Year; |
| unsigned NextYear;unsigned int NextYear; |
| // operating with variables#include <iostream>using namespace std;int main (){ // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0;} | 4 |
| int a = 0; |
| int a (0); |
| // initialization of variables#include <iostream>using namespace std;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; return 0;} | 6 |
| // my first string#include <iostream>#include <string>using namespace std;int main (){ string mystring = "This is a string"; cout << mystring; return 0;} | This is a string |
| string mystring = "This is a string";string mystring ("This is a string"); |
| // my first string#include <iostream>#include <string>using namespace 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;} | This is the initial string contentThis is a different string content |
| Constants | |
| a = 5; |
| 1776707-273 |
| 75 // decimal0113 // octal0x4b // hexadecimal |
| 75 // int75u // unsigned int75l // long75ul // unsigned long |
| 3.14159 // 3.141596.02e23 // 6.02 x 10231.6e-19 // 1.6 x 10-193.0 // 3.0 |
| 3.14159L // long double6.02e23f // float |
| 'z''p'"Hello world""How do you do?" |
| x'x' |
| \n | newline |
| \r | carriage return |
| \t | tab |
| \v | vertical tab |
| \b | backspace |
| \f | form feed (page feed) |
| \a | alert (beep) |
| \' | single quote (') |
| \" | double quote (") |
| \? | question mark (?) |
| \\ | backslash (\) |
| '\n''\t'"Left \t Right""one\ntwo\nthree" |
| "string expressed in \two lines" |
| "this forms" "a single" "string" "of characters" |
| L"This is a wide character string" |
| #define PI 3.14159265#define NEWLINE '\n' |
| // defined constants: calculate circumference#include <iostream>using namespace 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;} | 31.4159 |
| const int pathwidth = 100;const char tabulator = '\t';const zipcode = 12440; |
| a = 5; |
| a = b; |
| // assignment operator#include <iostream>using namespace std;int main (){ int a, b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 cout << "a:"; cout << a; cout << " b:"; cout << b; return 0;} | a:4 b:7 |
| a = 2 + (b = 5); |
| b = 5;a = 2 + b; |
| a = b = c = 5; |
| + | addition |
| - | subtraction |
| * | multiplication |
| / | division |
| % | modulo |
| a = 11 % 3; |
| expression | is equivalent to |
| value += increase; | value = value + increase; |
| a -= 5; | a = a - 5; |
| a /= b; | a = a / b; |
| price *= units + 1; | price = price * (units + 1); |
| // compound assignment operators#include <iostream>using namespace std;int main (){ int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0;} | 5 |
| c++;c+=1;c=c+1; |
| Example 1 | Example 2 |
| B=3; A=++B; // A contains 4, B contains 4 | B=3; A=B++; // A contains 3, B contains 4 |
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
| (7 == 5) // evaluates to false.(5 > 4) // evaluates to true.(3 != 2) // evaluates to true.(6 >= 6) // evaluates to true.(5 < 5) // evaluates to false. |
| (a == 5) // evaluates to false since a is not equal to 5.(a*b >= c) // evaluates to true since (2*3 >= 6) is true. (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false. ((b=2) == a) // evaluates to true. |
| !(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true. !(6 <= 4) // evaluates to true because (6 <= 4) would be false. !true // evaluates to false!false // evaluates to true. |
| a | b | a && b |
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
| a | b | a || b |
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
| ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ). |
| 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.5>3 ? a : b // returns the value of a, since 5 is greater than 3.a>b ? a : b // returns whichever is greater, a or b. |
| // conditional operator#include <iostream>using namespace std;int main (){ int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c; return 0;} | 7 |
| a = (b=3, b+2); |
| operator | asm equivalent | description |
| & | AND | Bitwise AND |
| | | OR | Bitwise Inclusive OR |
| ^ | XOR | Bitwise Exclusive OR |
| ~ | NOT | Unary complement (bit inversion) |
| << | SHL | Shift Left |
| >> | SHR | Shift Right |
| int i;float f = 3.14;i = (int) f; |
| i = int ( f ); |
| a = sizeof (char); |
| a = 5 + 7 % 2 |
| a = 5 + (7 % 2) // with a result of 6, ora = (5 + 7) % 2 // with a result of 0 |
| Level | Operator | Description | Grouping |
| 1 | :: | scope | Left-to-right |
| 2 | () [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid | postfix | Left-to-right |
| 3 | ++ -- ~ ! sizeof new delete | unary (prefix) | Right-to-left |
| * & | indirection and reference (pointers) | ||
| + - | unary sign operator | ||
| 4 | (type) | type casting | Right-to-left |
| 5 | .* ->* | pointer-to-member | Left-to-right |
| 6 | * / % | multiplicative | Left-to-right |
| 7 | + - | additive | Left-to-right |
| 8 | << >> | shift | Left-to-right |
| 9 | < > <= >= | relational | Left-to-right |
| 10 | == != | equality | Left-to-right |
| 11 | & | bitwise AND | Left-to-right |
| 12 | ^ | bitwise XOR | Left-to-right |
| 13 | | | bitwise OR | Left-to-right |
| 14 | && | logical AND | Left-to-right |
| 15 | || | logical OR | Left-to-right |
| 16 | ?: | conditional | Right-to-left |
| 17 | = *= /= %= += -= >>= <<= &= ^= != | assignment | Right-to-left |
| 18 | , | comma | Left-to-right |
| a = 5 + 7 % 2; |
| a = 5 + (7 % 2); |
| a = (5 + 7) % 2; |
| cout << "Output sentence"; // prints Output sentence on screencout << 120; // prints number 120 on screencout << x; // prints the content of x on screen |
| cout << "Hello"; // prints Hellocout << Hello; // prints the content of Hello variable |
| cout << "Hello, " << "I am " << "a C++ statement"; |
| cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode; |
| Hello, I am 24 years old and my zipcode is 90064 |
| cout << "This is a sentence.";cout << "This is another sentence."; |
| cout << "First sentence.\n ";cout << "Second sentence.\nThird sentence."; |
| cout << "First sentence." << endl;cout << "Second sentence." << endl; |
| int age;cin >> age; |
| // i/o example#include <iostream>using namespace std;int main (){ int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0;} | Please enter an integer value: 702The value you entered is 702 and its double is 1404. |
| cin >> a >> b; |
| cin >> a;cin >> b; |
| cin >> mystring; |
| // cin with strings#include <iostream>#include <string>using namespace std;int main (){ string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0;} | What's your name? Juan SouliéHello Juan Soulié.What is your favorite team? The IsotopesI like The Isotopes too! |
| string mystr ("1204");int myint;stringstream(mystr) >> myint; |
| // stringstreams#include <iostream>#include <string>#include <sstream>using namespace std;int main (){ string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); stringstream(mystr) >> price; cout << "Enter quantity: "; getline (cin,mystr); stringstream(mystr) >> quantity; cout << "Total price: " << price*quantity << endl; return 0;} | Enter price: 22.25Enter quantity: 7Total price: 155.75 |
| Control Structures | |
| if (x == 100) cout << "x is 100"; |
| if (x == 100){ cout << "x is "; cout << x;} |
| if (x == 100) cout << "x is 100";else cout << "x is not 100"; |
| if (x > 0) cout << "x is positive";else if (x < 0) cout << "x is negative";else cout << "x is 0"; |
| // custom countdown using while#include <iostream>using namespace std;int main (){ int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!\n"; return 0;} | Enter the starting number > 88, 7, 6, 5, 4, 3, 2, 1, FIRE! |
| // number echoer#include <iostream>using namespace std;int main (){ unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0;} | Enter number (0 to end): 12345You entered: 12345Enter number (0 to end): 160277You entered: 160277Enter number (0 to end): 0You entered: 0 |
| // countdown using a for loop#include <iostream>using namespace std;int main (){ for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!\n"; return 0;} | 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! |
| for ( n=0, i=100 ; n!=i ; n++, i-- ){ // whatever here...} |
| // break loop example#include <iostream>using namespace std;int main (){ int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0;} | 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! |
| // continue loop example#include <iostream>using namespace std;int main (){ for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0;} | 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! |
| // goto loop example#include <iostream>using namespace std;int main (){ int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!\n"; return 0;} | 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! |
| void exit (int exitcode); |
| switch example | if-else equivalent |
| switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; } | if (x == 1) { cout << "x is 1"; }else if (x == 2) { cout << "x is 2"; }else { cout << "value of x unknown"; } |
| switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; } |
| // function example#include <iostream>using namespace std;int addition (int a, int b){ int r; r=a+b; return (r);}int main (){ int z; z = addition (5,3); cout << "The result is " << z; return 0;} | The result is 8 |
| return (r); |
| cout << "The result is " << z; |
| // function example#include <iostream>using namespace std;int subtraction (int a, int b){ int r; r=a-b; return (r);}int main (){ int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0;} | The first result is 5The second result is 5The third result is 2The fourth result is 6 |
| z = subtraction (7,2);cout << "The first result is " << z; |
| z = 5;cout << "The first result is " << z; |
| cout << "The second result is " << subtraction (7,2); |
| cout << "The second result is " << 5; |
| cout << "The third result is " << subtraction (x,y); |
| z = 4 + subtraction (x,y); |
| z = subtraction (x,y) + 4; |
| z = 4 + 2;z = 2 + 4; |
| // void function example#include <iostream>using namespace std;void printmessage (){ cout << "I'm a function!";}int main (){ printmessage (); return 0;} | I'm a function! |
| void printmessage (void){ cout << "I'm a function!";} |
| printmessage (); |
| printmessage; | ||
| Functions (II) | | |
| int x=5, y=3, z;z = addition ( x , y ); |
| // passing parameters by reference#include <iostream>using namespace std;void duplicate (int& a, int& b, int& c){ a*=2; b*=2; c*=2;}int main (){ int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0;} | x=2, y=6, z=14 |
| void duplicate (int& a, int& b, int& c) |
| void duplicate (int a, int b, int c) |
| // more than one returning value#include <iostream>using namespace std;void prevnext (int x, int& prev, int& next){ prev = x-1; next = x+1;}int main (){ int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0;} | Previous=99, Next=101 |
| // default values in functions#include <iostream>using namespace std;int divide (int a, int b=2){ int r; r=a/b; return (r);}int main (){ cout << divide (12); cout << endl; cout << divide (20,4); return 0;} | 65 |
| divide (12) |
| divide (20,4) |
| // overloaded function#include <iostream>using namespace std;int operate (int a, int b){ return (a*b);}float operate (float a, float b){ return (a/b);}int main (){ int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0;} | 102.5 |
| // factorial calculator#include <iostream>using namespace std;long factorial (long a){ if (a > 1) return (a * factorial (a-1)); else return (1);}int main (){ long number; cout << "Please type a number: "; cin >> number; cout << number << "! = " << factorial (number); return 0;} | Please type a number: 99! = 362880 |
| int protofunction (int first, int second);int protofunction (int, int); |
| // declaring functions prototypes#include <iostream>using namespace std;void odd (int a);void even (int a);int main (){ int i; do { cout << "Type a number (0 to exit): "; cin >> i; odd (i); } while (i!=0); return 0;}void odd (int a){ if ((a%2)!=0) cout << "Number is odd.\n"; else even (a);}void even (int a){ if ((a%2)==0) cout << "Number is even.\n"; else odd (a);} | Type a number (0 to exit): 9Number is odd.Type a number (0 to exit): 6Number is even.Type a number (0 to exit): 1030Number is even.Type a number (0 to exit): 0Number is even. |
| void odd (int a);void even (int a); |
| Arrays | |
| int billy [5]; |
| int billy [5] = { 16, 2, 77, 40, 12071 }; |
| int billy [] = { 16, 2, 77, 40, 12071 }; |
| billy[2] = 75; |
| a = billy[2]; |
| int billy[5]; // declaration of a new arraybilly[2] = 75; // access to an element of the array. |
| billy[0] = a;billy[a] = 75;b = billy [a+2];billy[billy[a]] = billy[2] + 5; |
| // arrays example#include <iostream>using namespace std;int billy [] = {16, 2, 77, 40, 12071};int n, result=0;int main (){ for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0;} | 12206 |
| int jimmy [3][5]; |
| jimmy[1][3] |
| char century [100][365][24][60][60]; |
| int jimmy [3][5]; // is equivalent toint jimmy [15]; // (3 * 5 = 15) |
| multidimensional array | pseudo-multidimensional array |
| #define WIDTH 5#define HEIGHT 3int jimmy [HEIGHT][WIDTH];int n,m;int main (){ for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); } return 0;} | #define WIDTH 5#define HEIGHT 3int jimmy [HEIGHT * WIDTH];int n,m;int main (){ for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n*WIDTH+m]=(n+1)*(m+1); } return 0;} |
| #define HEIGHT 3 |
| #define HEIGHT 4 |
| void procedure (int arg[]) |
| int myarray [40]; |
| procedure (myarray); |
| // arrays as parameters#include <iostream>using namespace std;void printarray (int arg[], int length) { for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n";}int main (){ int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); return 0;} | 5 10 152 4 6 8 10 |
| base_type[][depth][depth] |
| void procedure (int myarray[][3][4]) |
For example, the following array:
Therefore, in this array, in theory, we can store sequences of characters up to 20 characters long. But we can also store shorter sequences. For example, jenny could store at some point in a program either the sequence "Hello" or the sequence "Merry christmas", since both are shorter than 20 characters. Therefore, since the array of characters can store shorter sequences than its total length, a special character is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\0' (backslash, zero). Our array of 20 elements of type char, called jenny, can be represented storing the characters sequences "Hello" and "Merry Christmas" as: Notice how after the valid content a null character ('\0') has been included in order to indicate the end of the sequence. The panels in gray color represent char elements with undetermined values. Initialization of null-terminated character sequencesBecause arrays of characters are ordinary arrays they follow all their same rules. For example, if we want to initialize an array of characters with some predetermined sequence of characters we can do it just like any other array:
But arrays of char elements have an additional method to initialize their values: using string literals. In the expressions we have used in some examples in previous chapters, constants that represent entire strings of characters have already showed up several times. These are specified enclosing the text to become a string literal between double quotes ("). For example:
Double quoted strings (") are literal constants whose type is in fact a null-terminated array of characters. So string literals enclosed between double quotes always have a null character ('\0') automatically appended at the end. Therefore we can initialize the array of char elements called myword with a null-terminated sequence of characters by either one of these two methods:
Please notice that we are talking about initializing an array of characters in the moment it is being declared, and not about assigning values to them once they have already been declared. In fact because this type of null-terminated arrays of characters are regular arrays we have the same restrictions that we have with any other array, so we are not able to copy blocks of data with an assignment operation. Assuming mytext is a char[] variable, expressions within a source code like:
Using null-terminated sequences of charactersNull-terminated sequences of characters are the natural way of treating strings in C++, so they can be used as such in many procedures. In fact, regular string literals have this type (char[]) and can also be used in most cases.For example, cin and cout support null-terminated sequences as valid containers for sequences of characters, so they can be used directly to extract strings of characters from cin or to insert them into cout. For example:
Finally, sequences of characters stored in char arrays can easily be converted into string objects just by using the assignment operator:
| |||||||||||||
| Pointers | | ||||||||||||
| ted = &andy; |
| andy = 25;fred = andy;ted = &andy; |
| beth = *ted; |
| beth = ted; // beth equal to ted ( 1776 )beth = *ted; // beth equal to value pointed by ted ( 25 ) |
| andy = 25;ted = &andy; |
| andy == 25&andy == 1776ted == 1776*ted == 25 |
| *ted == andy |
| int * number;char * character;float * greatnumber; |
| // my first pointer#include <iostream>using namespace std;int main (){ int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0;} | firstvalue is 10secondvalue is 20 |
| // more pointers#include <iostream>using namespace std;int main (){ int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed by p1 = 10 *p2 = *p1; // value pointed by p2 = value pointed by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0;} | firstvalue is 10secondvalue is 20 |
| int * p1, * p2; |
| int * p1, p2; |
| int numbers [20];int * p; |
| p = numbers; |
| numbers = p; |
| // more pointers#include <iostream>using namespace std;int main (){ int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; return 0;} | 10, 20, 30, 40, 50, |
| a[5] = 0; // a [offset of 5] = 0*(a+5) = 0; // pointed by (a+5) = 0 |
| int number;int *tommy = &number; |
| int number;int *tommy;tommy = &number; |
| int number;int *tommy;*tommy = &number; |
| char * terry = "hello"; |
| *(terry+4)terry[4] |
| char *mychar;short *myshort;long *mylong; |
| mychar++;myshort++;mylong++; |
| mychar = mychar + 1;myshort = myshort + 1;mylong = mylong + 1; |
| *p++ |
| *p++ = *q++; |
| *p = *q;++p;++q; |
| char a;char * b;char ** c;a = 'z';b = &a;c = &b; |
| // increaser#include <iostream>using namespace std;void increase (void* data, int size){ switch (size) { case sizeof(char) : (*((char*)data))++; break; case sizeof(int) : (*((int*)data))++; break; }}int main (){ char a = 'x'; int b = 1602; increase (&a,sizeof(a)); increase (&b,sizeof(b)); cout << a << ", " << b << endl; return 0;} | y, 1603 |
| int * p;p = 0; // p has a null pointer value |
| // pointer to functions#include <iostream>using namespace std;int addition (int a, int b){ return (a+b); }int subtraction (int a, int b){ return (a-b); }int operation (int x, int y, int (*functocall)(int,int)){ int g; g = (*functocall)(x,y); return (g);}int main (){ int m,n; int (*minus)(int,int) = subtraction; m = operation (7, 5, addition); n = operation (20, m, minus); cout <<n; return 0;} | 8 |
| int (* minus)(int,int) = subtraction; |
| Dynamic Memory | |
| int * bobby;bobby = new int [5]; |
| bobby = new int [5]; // if it fails an exception is thrown |
| bobby = new (nothrow) int [5]; |
| int * bobby;bobby = new (nothrow) int [5];if (bobby == 0) { // error assigning memory. Take measures. }; |
| delete pointer;delete [] pointer; |
| // rememb-o-matic#include <iostream>using namespace std;int main (){ int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new (nothrow) int[i]; if (p == 0) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n++) { cout << "Enter number: "; cin >> p[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << p[n] << ", "; delete[] p; } return 0;} | How many numbers would you like to type? 5Enter number : 75Enter number : 436Enter number : 1067Enter number : 8Enter number : 32You have entered: 75, 436, 1067, 8, 32, |
| p= new (nothrow) int[i]; |
| struct product { int weight; float price;} ;product apple;product banana, melon; |
| struct product { int weight; float price;} apple, banana, melon; |
| apple.weightapple.pricebanana.weightbanana.pricemelon.weightmelon.price |
| // example about structures#include <iostream>#include <string>#include <sstream>using namespace std;struct movies_t { string title; int year;} mine, yours;void printmovie (movies_t movie);int main (){ string mystr; mine.title = "2001 A Space Odyssey"; mine.year = 1968; cout << "Enter title: "; getline (cin,yours.title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> yours.year; cout << "My favorite movie is:\n "; printmovie (mine); cout << "And yours is:\n "; printmovie (yours); return 0;}void printmovie (movies_t movie){ cout << movie.title; cout << " (" << movie.year << ")\n";} | Enter title: AlienEnter year: 1979My favorite movie is: 2001 A Space Odyssey (1968)And yours is: Alien (1979) |
| // array of structures#include <iostream>#include <string>#include <sstream>using namespace std;#define N_MOVIES 3struct movies_t { string title; int year;} films [N_MOVIES];void printmovie (movies_t movie);int main (){ string mystr; int n; for (n=0; n<N_MOVIES; n++) { cout << "Enter title: "; getline (cin,films[n].title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> films[n].year; } cout << "\nYou have entered these movies:\n"; for (n=0; n<N_MOVIES; n++) printmovie (films[n]); return 0;}void printmovie (movies_t movie){ cout << movie.title; cout << " (" << movie.year << ")\n";} | Enter title: Blade RunnerEnter year: 1982Enter title: MatrixEnter year: 1999Enter title: Taxi DriverEnter year: 1976 You have entered these movies:Blade Runner (1982)Matrix (1999)Taxi Driver (1976) |
| struct movies_t { string title; int year;};movies_t amovie;movies_t * pmovie; |
| pmovie = &amovie; |
| // pointers to structures#include <iostream>#include <string>#include <sstream>using namespace std;struct movies_t { string title; int year;};int main (){ string mystr; movies_t amovie; movies_t * pmovie; pmovie = &amovie; cout << "Enter title: "; getline (cin, pmovie->title); cout << "Enter year: "; getline (cin, mystr); (stringstream) mystr >> pmovie->year; cout << "\nYou have entered:\n"; cout << pmovie->title; cout << " (" << pmovie->year << ")\n"; return 0;} | Enter title: Invasion of the body snatchersEnter year: 1978 You have entered:Invasion of the body snatchers (1978) |
| pmovie->title |
| (*pmovie).title |
| *pmovie.title |
| *(pmovie.title) |
| Expression | What is evaluated | Equivalent |
| a.b | Member b of object a | |
| a->b | Member b of object pointed by a | (*a).b |
| *a.b | Value pointed by member b of object a | *(a.b) |
| struct movies_t { string title; int year;};struct friends_t { string name; string email; movies_t favorite_movie; } charlie, maria;friends_t * pfriends = &charlie; |
| charlie.namemaria.favorite_movie.titlecharlie.favorite_movie.yearpfriends->favorite_movie.year |
| Other Data Types | |
| typedef char C;typedef unsigned int WORD;typedef char * pChar;typedef char field [50]; |
| C mychar, anotherchar, *ptc1;WORD myword;pChar ptc2;field name; |
| union mytypes_t { char c; int i; float f; } mytypes; |
| mytypes.cmytypes.imytypes.f |
| union mix_t { long l; struct { short hi; short lo; } s; char c[4];} mix; |
| structure with regular union | structure with anonymous union |
| struct { char title[50]; char author[50]; union { float dollars; int yens; } price;} book; | struct { char title[50]; char author[50]; union { float dollars; int yens; };} book; |
| book.price.dollarsbook.price.yens |
| book.dollarsbook.yens |
| enum colors_t {black, blue, green, cyan, red, purple, yellow, white}; |
| colors_t mycolor; mycolor = blue;if (mycolor == green) mycolor = red; |
| enum months_t { january=1, february, march, april, may, june, july, august, september, october, november, december} y2k; |
| Classes (I) | |
| class CRectangle { int x, y; public: void set_values (int,int); int area (void); } rect; |
| int a; |
| rect.set_values (3,4);myarea = rect.area(); |
| // classes example#include <iostream>using namespace std;class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);}};void CRectangle::set_values (int a, int b) { x = a; y = b;}int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0;} | area: 12 |
| // example: one class, two objects#include <iostream>using namespace std;class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);}};void CRectangle::set_values (int a, int b) { x = a; y = b;}int main () { CRectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} | rect area: 12rectb area: 30 |
| // example: class constructor#include <iostream>using namespace std;class CRectangle { int width, height; public: CRectangle (int,int); int area () {return (width*height);}};CRectangle::CRectangle (int a, int b) { width = a; height = b;}int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} | rect area: 12rectb area: 30 |
| CRectangle rect (3,4);CRectangle rectb (5,6); |
| // example on constructors and destructors#include <iostream>using namespace std;class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () {return (*width * *height);}};CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b;}CRectangle::~CRectangle () { delete width; delete height;}int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} | rect area: 12rectb area: 30 |
| // overloading class constructors#include <iostream>using namespace std;class CRectangle { int width, height; public: CRectangle (); CRectangle (int,int); int area (void) {return (width*height);}};CRectangle::CRectangle () { width = 5; height = 5;}CRectangle::CRectangle (int a, int b) { width = a; height = b;}int main () { CRectangle rect (3,4); CRectangle rectb; cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} | rect area: 12rectb area: 25 |
| CRectangle rectb; // rightCRectangle rectb(); // wrong! |
| class CExample { public: int a,b,c; void multiply (int n, int m) { a=n; b=m; c=a*b; }; }; |
| CExample ex; |
| class CExample { public: int a,b,c; CExample (int n, int m) { a=n; b=m; }; void multiply () { c=a*b; }; }; |
| CExample ex (2,3); |
| CExample ex; |
| CExample::CExample (const CExample& rv) { a=rv.a; b=rv.b; c=rv.c; } |
| CExample ex (2,3);CExample ex2 (ex); // copy constructor (data copied from ex) |
| CRectangle * prect; |
| // pointer to classes example#include <iostream>using namespace std;class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return (width * height);}};void CRectangle::set_values (int a, int b) { width = a; height = b;}int main () { CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b->set_values (3,4); d->set_values (5,6); d[1].set_values (7,8); cout << "a area: " << a.area() << endl; cout << "*b area: " << b->area() << endl; cout << "*c area: " << c->area() << endl; cout << "d[0] area: " << d[0].area() << endl; cout << "d[1] area: " << d[1].area() << endl; return 0;} | a area: 2*b area: 12*c area: 2d[0] area: 30d[1] area: 56 |
| expression | can be read as |
| *x | pointed by x |
| &x | address of x |
| x.y | member y of object x |
| x->y | member y of object pointed by x |
| (*x).y | member y of object pointed by x (equivalent to the previous one) |
| x[0] | first object pointed by x |
| x[1] | second object pointed by x |
| x[n] | (n+1)th object pointed by x |
| Classes (II) | |
| int a, b, c;a = b + c; |
| struct { string product; float price;} a, b, c;a = b + c; |
| Overloadable operators |
| + - * / = < > += -= *= /= << >><<= >>= == != <= >= ++ -- % & ^ ! |~ &= ^= |= && || %= [] () , ->* -> new delete new[] delete[] |
| // vectors: overloading operators example#include <iostream>using namespace std;class CVector { public: int x,y; CVector () {}; CVector (int,int); CVector operator + (CVector);};CVector::CVector (int a, int b) { x = a; y = b;}CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp);}int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0;} | 4,3 |
| CVector (int, int); // function name CVector (constructor)CVector operator+ (CVector); // function returns a CVector |
| c = a + b;c = a.operator+ (b); |
| CVector () { }; |
| CVector (int, int); |
| CVector c; |
| CVector () { x=0; y=0; }; |
| CVector d (2,3);CVector e;e = d; // copy assignment operator |
| Expression | Operator | Member function | Global function |
| @a | + - * & ! ~ ++ -- | A::operator@() | operator@(A) |
| a@ | ++ -- | A::operator@(int) | operator@(A,int) |
| a@b | + - * / % ^ & | < > == != <= >= << >> && || , | A::operator@ (B) | operator@(A,B) |
| a@b | = += -= *= /= %= ^= &= |= <<= >>= [] | A::operator@ (B) | - |
| a(b, c...) | () | A::operator() (B, C...) | - |
| a->x | -> | A::operator->() | - |
| // this#include <iostream>using namespace std;class CDummy { public: int isitme (CDummy& param);};int CDummy::isitme (CDummy& param){ if (¶m == this) return true; else return false;}int main () { CDummy a; CDummy* b = &a; if ( b->isitme(a) ) cout << "yes, &a is b"; return 0;} | yes, &a is b |
| CVector& CVector::operator= (const CVector& param){ x=param.x; y=param.y; return *this;} |
| // static members in classes#include <iostream>using namespace std;class CDummy { public: static int n; CDummy () { n++; }; ~CDummy () { n--; };};int CDummy::n=0;int main () { CDummy a; CDummy b[5]; CDummy * c = new CDummy; cout << a.n << endl; delete c; cout << CDummy::n << endl; return 0;} | 76 |
| int CDummy::n=0; |
| cout << a.n;cout << CDummy::n; |
| Statement: | Explained in: |
| int a::b(c) {}; | Classes |
| a->b | Pointers |
| class a: public b; | Friendship and inheritance |
| // pointers to base class#include <iostream>using namespace std;class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } };class CRectangle: public CPolygon { public: int area () { return (width * height); } };class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } };int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = ▭ CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;} | 2010 |
| // virtual members#include <iostream>using namespace std;class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area () { return (0); } };class CRectangle: public CPolygon { public: int area () { return (width * height); } };class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } };int main () { CRectangle rect; CTriangle trgl; CPolygon poly; CPolygon * ppoly1 = ▭ CPolygon * ppoly2 = &trgl; CPolygon * ppoly3 = &poly; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly3->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; cout << ppoly3->area() << endl; return 0;} | 20100 |
| // abstract class CPolygonclass CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area () =0;}; |
| CPolygon poly; |
| CPolygon * ppoly1;CPolygon * ppoly2; |
| // abstract base class#include <iostream>using namespace std;class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; };class CRectangle: public CPolygon { public: int area (void) { return (width * height); } };class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } };int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = ▭ CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; return 0;} | 2010 |
| // pure virtual members can be called// from the abstract base class#include <iostream>using namespace std;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 << this->area() << endl; } };class CRectangle: public CPolygon { public: int area (void) { return (width * height); } };class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } };int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = ▭ CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); return 0;} | 2010 |
| // dynamic allocation and polymorphism#include <iostream>using namespace std;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 << this->area() << endl; } };class CRectangle: public CPolygon { public: int area (void) { return (width * height); } };class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } };int main () { CPolygon * ppoly1 = new CRectangle; CPolygon * ppoly2 = new CTriangle; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); ppoly2->printarea(); delete ppoly1; delete ppoly2; return 0;} | 2010 |
| CPolygon * ppoly1 = new CRectangle;CPolygon * ppoly2 = new CTriangle; |
| Templates | |
| template <class myType>myType GetMax (myType a, myType b) { return (a>b?a:b);} |
| int x,y;GetMax <int> (x,y); |
| // function template#include <iostream>using namespace std;template <class T>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<int>(i,j); n=GetMax<long>(l,m); cout << k << endl; cout << n << endl; return 0;} | 610 |
| T result; |
| int i,j;GetMax (i,j); |
| // function template II#include <iostream>using namespace std;template <class T>T GetMax (T a, T b) { return (a>b?a:b);}int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout << k << endl; cout << n << endl; return 0;} | 610 |
| int i;long l;k = GetMax (i,l); |
| template <class T, class U>T GetMin (T a, U b) { return (a<b?a:b);} |
| int i,j;long l;i = GetMin<int,long> (j,l); |
| i = GetMin (j,l); |
| template <class T>class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; }}; |
| mypair<int> myobject (115, 36); |
| mypair<double> myfloats (3.0, 2.18); |
| // class templates#include <iostream>using namespace std;template <class T>class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax ();};template <class T>T mypair<T>::getmax (){ T retval; retval = a>b? a : b; return retval;}int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0;} | 100 |
| template <class T>T mypair<T>::getmax () |
| // template specialization#include <iostream>using namespace std;// class template:template <class T>class mycontainer { T element; public: mycontainer (T arg) {element=arg;} T increase () {return ++element;}};// class template specialization:template <>class mycontainer <char> { char element; public: mycontainer (char arg) {element=arg;} char uppercase ();};// member of class template specialization:template <>char mycontainer<char>::uppercase(){ if ((element>='a')&&(element<='z')) element+='A'-'a'; return element;}int main () { mycontainer<int> myint (7); mycontainer<char> mychar ('j'); cout << myint.increase() << endl; cout << mychar.uppercase() << endl; return 0;} | 8J |
| template <> class mycontainer <char> { ... }; |
| template <class T> class mycontainer { ... };template <> class mycontainer <char> { ... }; |
| // sequence template#include <iostream>using namespace std;template <class T, int N>class mysequence { T memblock [N]; public: void setmember (int x, T value); T getmember (int x);};template <class T, int N>void mysequence<T,N>::setmember (int x, T value) { memblock[x]=value;}template <class T, int N>T mysequence<T,N>::getmember (int x) { return memblock[x];}int main () { mysequence <int,5> myints; mysequence <double,5> myfloats; myints.setmember (0,100); myfloats.setmember (3,3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0;} | 1003.1416 |
| template <class T=char, int N=10> class mysequence {..}; |
| mysequence<> myseq; |
| mysequence<char,10> myseq; |
| Namespaces | |
| namespace myNamespace{ int a, b;} |
| myNamespace::amyNamespace::b |
| // namespaces#include <iostream>using namespace std;namespace first{ int var = 5;}namespace second{ double var = 3.1416;}int main () { cout << first::var << endl; cout << second::var << endl; return 0;} | 53.1416 |
| // using#include <iostream>using namespace std;namespace first{ int x = 5; int y = 10;}namespace second{ double x = 3.1416; double y = 2.7183;}int main () { using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0;} | 52.7183103.1416 |
| // using#include <iostream>using namespace std;namespace first{ int x = 5; int y = 10;}namespace second{ double x = 3.1416; double y = 2.7183;}int main () { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0;} | 5103.14162.7183 |
| // using namespace example#include <iostream>using namespace std;namespace first{ int x = 5;}namespace second{ double x = 3.1416;}int main () { { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0;} | 53.1416 |
| Exceptions | |
| // exceptions#include <iostream>using namespace std;int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. " << e << endl; } return 0;} | An exception occurred. Exception Nr. 20 |
| throw 20; |
| try { // code here}catch (int param) { cout << "int exception"; }catch (char param) { cout << "char exception"; }catch (...) { cout << "default exception"; } |
| try { try { // code here } catch (int n) { throw; }}catch (...) { cout << "Exception occurred";} |
| float myfunction (char param) throw (int); |
| int myfunction (int param) throw(); // no exceptions allowedint myfunction (int param); // all exceptions allowed |
| // standard exceptions#include <iostream>#include <exception>using namespace std;class myexception: public exception{ virtual const char* what() const throw() { return "My exception happened"; }} myex;int main () { try { throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0;} | My exception happened. |
| exception | description |
| bad_alloc | thrown by new on allocation failure |
| bad_cast | thrown by dynamic_cast when fails with a referenced type |
| bad_exception | thrown when an exception type doesn't match any catch |
| bad_typeid | thrown by typeid |
| ios_base::failure | thrown by functions in the iostream library |
| try{ int * myarray= new int[1000];}catch (bad_alloc&){ cout << "Error allocating memory." << endl;} |
| // bad_alloc standard exception#include <iostream>#include <exception>using namespace std;int main () { try { int* myarray= new int[1000]; } catch (exception& e) { cout << "Standard exception: " << e.what() << endl; } return 0;} | ||
| Type Casting | | |
| short a=2000;int b;b=a; |
| class A {};class B { public: B (A a) {} };A a;B b=a; |
| short a=2000;int b;b = (int) a; // c-like cast notationb = int (a); // functional notation |
| // class type-casting#include <iostream>using namespace std;class CDummy { float i,j;};class CAddition { int x,y; public: CAddition (int a, int b) { x=a; y=b; } int result() { return x+y;}};int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd->result(); return 0;} |
| padd = (CAddition*) &d; |
| class CBase { };class CDerived: public CBase { };CBase b; CBase* pb;CDerived d; CDerived* pd;pb = dynamic_cast<CBase*>(&d); // ok: derived-to-basepd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived |
| // dynamic_cast#include <iostream>#include <exception>using namespace std;class CBase { virtual void dummy() {} };class CDerived: public CBase { int a; };int main () { try { CBase * pba = new CDerived; CBase * pbb = new CBase; CDerived * pd; pd = dynamic_cast<CDerived*>(pba); if (pd==0) cout << "Null pointer on first type-cast" << endl; pd = dynamic_cast<CDerived*>(pbb); if (pd==0) cout << "Null pointer on second type-cast" << endl; } catch (exception& e) {cout << "Exception: " << e.what();} return 0;} | Null pointer on second type-cast |
| Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly. |
| CBase * pba = new CDerived;CBase * pbb = new CBase; |
| class CBase {};class CDerived: public CBase {};CBase * a = new CBase;CDerived * b = static_cast<CDerived*>(a); |
| double d=3.14159265;int i = static_cast<int>(d); |
| class A {};class B {};A * a = new A;B * b = reinterpret_cast<B*>(a); |
| // const_cast#include <iostream>using namespace std;void print (char * str){ cout << str << endl;}int main () { const char * c = "sample text"; print ( const_cast<char *> (c) ); return 0;} | sample text |
| // typeid#include <iostream>#include <typeinfo>using namespace std;int main () { int * a,b; a=0; b=0; if (typeid(a) != typeid(b)) { cout << "a and b are of different types:\n"; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; } return 0;} | a and b are of different types:a is: int *b is: int |
| // typeid, polymorphic class#include <iostream>#include <typeinfo>#include <exception>using namespace std;class CBase { virtual void f(){} };class CDerived : public CBase {};int main () { try { CBase* a = new CBase; CBase* b = new CDerived; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; cout << "*a is: " << typeid(*a).name() << '\n'; cout << "*b is: " << typeid(*b).name() << '\n'; } catch (exception& e) { cout << "Exception: " << e.what() << endl; } return 0;} | a is: class CBase *b is: class CBase **a is: class CBase*b is: class CDerived |
| Preprocessor directives | |
| #define TABLE_SIZE 100int table1[TABLE_SIZE];int table2[TABLE_SIZE]; |
| int table1[100];int table2[100]; |
| #define getmax(a,b) a>b?a:b |
| // function macro#include <iostream>using namespace std;#define getmax(a,b) ((a)>(b)?(a):(b))int main(){ int x=5, y; y= getmax(x,2); cout << y << endl; cout << getmax(7,x) << endl; return 0;} | 57 |
| #define TABLE_SIZE 100int table1[TABLE_SIZE];#undef TABLE_SIZE#define TABLE_SIZE 200int table2[TABLE_SIZE]; |
| int table1[100];int table2[200]; |
| #define str(x) #xcout << str(test); |
| cout << "test"; |
| #define glue(a,b) a ## bglue(c,out) << "test"; |
| cout << "test"; |
| #ifdef TABLE_SIZEint table[TABLE_SIZE];#endif |
| #ifndef TABLE_SIZE#define TABLE_SIZE 100#endifint table[TABLE_SIZE]; |
| #if TABLE_SIZE>200#undef TABLE_SIZE#define TABLE_SIZE 200 #elif TABLE_SIZE<50#undef TABLE_SIZE#define TABLE_SIZE 50 #else#undef TABLE_SIZE#define TABLE_SIZE 100#endif int table[TABLE_SIZE]; |
| #if !defined TABLE_SIZE#define TABLE_SIZE 100#elif defined ARRAY_SIZE#define TABLE_SIZE ARRAY_SIZEint table[TABLE_SIZE]; |
| #line 20 "assigning variable"int a?; |
| #ifndef __cplusplus#error A C++ compiler is required!#endif |
| #include "file"#include <file> |
| macro | value |
| __LINE__ | Integer value representing the current line in the source code file being compiled. |
| __FILE__ | A string literal containing the presumed name of the source file being compiled. |
| __DATE__ | A string literal in the form "Mmm dd yyyy" containing the date in which the compilation process began. |
| __TIME__ | A string literal in the form "hh:mm:ss" containing the time at which the compilation process began. |
| __cplusplus | An integer value. All C++ compilers have this constant defined to some value. If the compiler is fully compliant with the C++ standard its value is equal or greater than 199711L depending on the version of the standard they comply. |
| // standard macro names#include <iostream>using namespace std;int main(){ cout << "This is the line number " << __LINE__; cout << " of file " << __FILE__ << ".\n"; cout << "Its compilation began " << __DATE__; cout << " at " << __TIME__ << ".\n"; cout << "The compiler gives a __cplusplus value of " << __cplusplus; return 0;} | ||
| Input/Output with files | | |
| // basic file operations#include <iostream>#include <fstream>using namespace std;int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0;} | [file example.txt]Writing this to a file |
| ios::in | Open for input operations. |
| ios::out | Open for output operations. |
| ios::binary | Open in binary mode. |
| ios::ate | Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file. |
| ios::app | All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. |
| ios::trunc | If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one. |
| ofstream myfile;myfile.open ("example.bin", ios::out | ios::app | ios::binary); |
| class | default mode parameter |
| ofstream | ios::out |
| ifstream | ios::in |
| fstream | ios::in | ios::out |
| ofstream myfile ("example.bin", ios::out | ios::app | ios::binary); |
| if (myfile.is_open()) { /* ok, proceed with output */ } |
| myfile.close(); |
| // writing on a text file#include <iostream>#include <fstream>using namespace std;int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0;} | [file example.txt]This is a line.This is another line. |
| // reading a text file#include <iostream>#include <fstream>#include <string>using namespace std;int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0;} | This is a line.This is another line. |
| ios::beg | offset counted from the beginning of the stream |
| ios::cur | offset counted from the current position of the stream pointer |
| ios::end | offset counted from the end of the stream |
| // obtaining file size#include <iostream>#include <fstream>using namespace std;int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0;} | size is: 40 bytes. |
| // reading a complete binary file#include <iostream>#include <fstream>using namespace std;ifstream::pos_type size;char * memblock;int main () { ifstream file ("example.txt", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout << "the complete file content is in memory"; delete[] memblock; } else cout << "Unable to open file"; return 0;} | the complete file content is in memory |
| ifstream::pos_type size; |
| int size;size = (int) file.tellg(); |
| memblock = new char[size]; |
| file.seekg (0, ios::beg);file.read (memblock, size);file.close(); |