esoft metro campus - programming with c++

257
Programming with C++ Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.

Upload: rasan-samarasinghe

Post on 19-Feb-2017

72 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Esoft Metro Campus - Programming with C++

Programming with C++

Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.

Page 2: Esoft Metro Campus - Programming with C++

Contents1. Overview of C++ Language2. C++ Program Structure3. C++ Basic Syntax4. Primitive Built-in types in C++5. Variable types6. typedef Declarations7. Enumerated Types8. Variable Scope9. Constants/Literals10. Storage Classes11. Operators12. Control Constructs13. Functions14. Math Operations in C++15. Arrays16. Multi-dimensional Arrays 17. Strings

18. C++ Pointers19. References20. Date and Time 21. Structures22. Basic Input / Output 23. Classes and Objects24. Inheritance25. Overloading 26. Polymorphism27. Interfaces 28. Files and Streams29. Exception Handling30. Dynamic Memory31. Namespaces32. Templates33. Preprocessor34. Multithreading

Page 3: Esoft Metro Campus - Programming with C++

Overview of C++ Language

• C++ is a statically typed, compiled, general purpose programming language.

• C++ Supports procedural, object-oriented and generic programming.

• C++ is a middle-level language.• C++ was developed by Bjarne Stroustrup starting in

1979 at Bell Labs as an enhancement to the C language.

• C++ is a superset of C and that virtually any legal C program is a legal C++ program.

Page 4: Esoft Metro Campus - Programming with C++

Use of C++

• C++ is used by hundreds of thousands of programmers in essentially every application domain.

• C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware.

• C++ is widely used for teaching and research. • Primary user interfaces of Apple Macintosh and

Windows are written in C++.

Page 5: Esoft Metro Campus - Programming with C++

A list of C++ Compilers

• C++ Builder• Turbo C++ Explorer• Borland C++• Clang• CodeWarrior• GCC• Intel C++ Compiler• Visual C++

Page 6: Esoft Metro Campus - Programming with C++

C++ Program Structure

#include <iostream> using namespace std; int main() { cout <<"Hello World"; return 0; }

Page 7: Esoft Metro Campus - Programming with C++

Compile & Execute C++ Program

• Open a text editor and add the code as above. • Save the file as: hello.cpp • Open a command prompt and go to the

directory where you saved the file. • Type 'g++ hello.cpp' and press enter to

compile your code. • Now, type ‘a’ and Enter to run your program.

Page 8: Esoft Metro Campus - Programming with C++

C++ Basic Syntax

• Semicolons• Case Sensitivity• C++ Identifiers• Comments

Page 9: Esoft Metro Campus - Programming with C++

Semicolons

• semicolon is a statement terminator. • Each individual statement must be ended with

a semicolon.

x = y; y = y+1; add(x, y);

Page 10: Esoft Metro Campus - Programming with C++

Case Sensitivity

C++ is a case-sensitive programming language.

Manpower and manpower

are two different identifiers in C++

Page 11: Esoft Metro Campus - Programming with C++

C++ Identifiers

• An identifier is a name used to identify a variable, function, class, module, or any other user-defined item.

• An identifier starts with a letter A to Z or a to z or an underscore followed by zero or more letters, underscores and digits.

Page 12: Esoft Metro Campus - Programming with C++

C++ Keywords

Page 13: Esoft Metro Campus - Programming with C++

Comments

// this is a single line comment

/* this is a multiline comment */

Page 14: Esoft Metro Campus - Programming with C++

Primitive Built-in types in C++

Page 15: Esoft Metro Campus - Programming with C++

Type modifiers

• signed • unsigned • short • long

Page 16: Esoft Metro Campus - Programming with C++

Variable types

Page 17: Esoft Metro Campus - Programming with C++

Variable Definition

Syntax:type variable_list;

Ex:int i, j, k; char c, ch; float f, salary; double d;

Page 18: Esoft Metro Campus - Programming with C++

Variable initializing

Variables can be initialized in their declaration.

Ex:int d = 3, f = 5; byte z = 22; char x = 'x';

Page 19: Esoft Metro Campus - Programming with C++

Variable Declaration

A variable declaration provides assurance to the compiler that there is one variable existing with the given type

Syntax:extern type variable_list;

Page 20: Esoft Metro Campus - Programming with C++

Variable Declaration#include <iostream> using namespace std; extern int a, b; // variable declaration int main () { int a, b; // variable definitiona =10; // initializationb =20; // initialization}

Page 21: Esoft Metro Campus - Programming with C++

typedef Declarations

You can create a new name for an existing type using typedef.

typedef type newname;

Ex:typedef int feet; // feet is another name for intfeet distance; // creates an int variable

Page 22: Esoft Metro Campus - Programming with C++

Enumerated Types

• An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type.

• Each enumerator is a constant whose type is the enumeration.

Page 23: Esoft Metro Campus - Programming with C++

Enumerated Types

Syntax:enum enum-name { list of names } var-list;

Examples: enum color { red, green, blue } c; /* default values are 0, 1, 2 */

c = blue;

enum color { red, green=5, blue }; /* values are 0, 5, 6 */

Page 24: Esoft Metro Campus - Programming with C++

Variable Scope

• Local Variables– Declared inside a function or block.

• Global Variables– Defined outside of all the functions.

Page 25: Esoft Metro Campus - Programming with C++

Local Variables

#include <iostream> using namespace std; int main () { int a, b, c; // Local variable declaration

// Initialization a =10; b =20; c = a + b; cout << c; return 0; }

Page 26: Esoft Metro Campus - Programming with C++

Global Variables#include <iostream> using namespace std; int g; // Global variable declaration int main () { int a, b; a =10; b =20; g = a + b; // Initialization cout << g; return 0; }

Page 27: Esoft Metro Campus - Programming with C++

Global Variables

#include <iostream> using namespace std; int g =20; // Global variable declaration int main () { int g =10; // Local variable declaration cout << g; return 0; }

Page 28: Esoft Metro Campus - Programming with C++

Default values of global variables

Page 29: Esoft Metro Campus - Programming with C++

Constants/Literals

• Integer literals• Floating-point literals• Boolean literals• Character literals• String literals

Page 30: Esoft Metro Campus - Programming with C++

Integer literals

85 // decimal 0213 // octal 0x4b // hexadecimal 30 // int 30u // unsigned int 30l // long 30ul // unsigned long

Page 31: Esoft Metro Campus - Programming with C++

Floating-point literals

3.14159 // Float314159E-5L // E notation

Page 32: Esoft Metro Campus - Programming with C++

Boolean literals

• A value of true representing true. • A value of false representing false.

Page 33: Esoft Metro Campus - Programming with C++

Character literals

A character literal can be a plain character ('x') or an escape sequence ('\t')

Page 34: Esoft Metro Campus - Programming with C++

Escape sequences

Page 35: Esoft Metro Campus - Programming with C++

String literals

"hello, dear" "hello, \ dear" "hello, ""d""ear"

Page 36: Esoft Metro Campus - Programming with C++

Defining Constants

• Using #define preprocessor. • Using const keyword.

Page 37: Esoft Metro Campus - Programming with C++

The #define Preprocessor

#define identifier value

Ex:#define LENGTH 10 #define WIDTH 5

Page 38: Esoft Metro Campus - Programming with C++

The const Keyword

const type variable = value;

Ex:const int LENGTH = 10; const int WIDTH = 5;

Page 39: Esoft Metro Campus - Programming with C++

Storage Classes• auto – default storage class for all local variables.

• register – used to define local variables that should be stored in a register

instead of RAM.• static – instructs the compiler to keep a local variable in existence

during the life-time of the program• extern – used to give a reference of a global variable that is visible to

ALL the program files. • mutable – applies only to class objects

Page 40: Esoft Metro Campus - Programming with C++

Operators

• Arithmetic Operators • Comparison Operators • Logical Operators • Bitwise Operators • Assignment Operators • Misc Operators

Page 41: Esoft Metro Campus - Programming with C++

Arithmetic Operators

A = 10, B = 20

Page 42: Esoft Metro Campus - Programming with C++

Comparison OperatorsA = 10, B = 20

Page 43: Esoft Metro Campus - Programming with C++

Logical Operators

A = 1, B = 0

Page 44: Esoft Metro Campus - Programming with C++

Bitwise OperatorsA = 60, B = 13

Page 45: Esoft Metro Campus - Programming with C++

Truth table

Page 46: Esoft Metro Campus - Programming with C++

Bitwise Operators

A = 00111100 B = 00001101 A&B = 00001100 A|B = 00111101 A^B = 00110001 ~A = 11000011

A = 60, B = 13

Page 47: Esoft Metro Campus - Programming with C++

Assignment Operators

Page 48: Esoft Metro Campus - Programming with C++

Misc Operators

Page 49: Esoft Metro Campus - Programming with C++

Operators Precedence

Page 50: Esoft Metro Campus - Programming with C++

Control Constructs

• If Statement• If… Else Statement• If… Else if… Else Statement• Switch Statement• The ? : Operator • While Loop• Do While Loop• For Loop

Page 51: Esoft Metro Campus - Programming with C++

If Statement

if(Boolean_expression){ //Statements will execute if the

Boolean expression is true}

Boolean Expression

Statements

True

False

Page 52: Esoft Metro Campus - Programming with C++

If… Else Statement

if(Boolean_expression){ //Executes when the Boolean expression is

true}else{ //Executes when the Boolean

expression is false}

Boolean Expression

Statements

True

False

Statements

Page 53: Esoft Metro Campus - Programming with C++

If… Else if… Else Statement

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true}else { //Executes when the none of the above condition is true.}

Page 54: Esoft Metro Campus - Programming with C++

If… Else if… Else Statement

Boolean expression 1

False

Statements

Boolean expression 2

Boolean expression 3

Statements

Statements

False

False

Statements

True

True

True

Page 55: Esoft Metro Campus - Programming with C++

Nested If Statement

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is

true }}

Boolean Expression 1

True

False

StatementsBoolean Expression 2

True

False

Page 56: Esoft Metro Campus - Programming with C++

Switch Statement

switch (value){ case constant: //statements break; case constant: //statements break; default: //statements}

Page 57: Esoft Metro Campus - Programming with C++

The ? : Operator

Exp1 ? Exp2 : Exp3;

Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire expression.

If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

Page 58: Esoft Metro Campus - Programming with C++

While Loop

while(Boolean_expression){ //Statements}

Boolean Expression

Statements

True

False

Page 59: Esoft Metro Campus - Programming with C++

Do While Loop

do{ //Statements}while(Boolean_expression);

Boolean Expression

Statements

True

False

Page 60: Esoft Metro Campus - Programming with C++

For Loop

for(initialization; Boolean_expression; update){ //Statements}

Boolean Expression

Statements

True

False

Update

Initialization

Page 61: Esoft Metro Campus - Programming with C++

break Statement

Boolean Expression

Statements

True

False

break

Page 62: Esoft Metro Campus - Programming with C++

continue Statement

Boolean Expression

Statements

True

False

continue

Page 63: Esoft Metro Campus - Programming with C++

Nested Loop

Boolean Expression

True

False

Boolean Expression

Statements

True

False

Page 64: Esoft Metro Campus - Programming with C++

Functions

• Function is a group of statements that together perform a task.

• Every C++ program has at least one function, which is main()

Page 65: Esoft Metro Campus - Programming with C++

Defining a Function

return_type function_name( parameter list ) { body of the function

}

Page 66: Esoft Metro Campus - Programming with C++

Example

int max(int num1, int num2) { int result; if (num1 > num2){ result = num1; }else{ result = num2; } return result; }

Page 67: Esoft Metro Campus - Programming with C++

Function Declarations

A function declaration tells the compiler about a function name and how to call the function.

return_type function_name( parameter list );

Ex:int max(int num1, int num2); int max(int, int);

Page 68: Esoft Metro Campus - Programming with C++

Calling a Function

int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b);

Page 69: Esoft Metro Campus - Programming with C++

Function Arguments

• Function call by value • Function call by pointer• Function call by reference

Page 70: Esoft Metro Campus - Programming with C++

Function call by value

passing arguments to a function copies the actual value of an argument into the formal parameter of the function.

Page 71: Esoft Metro Campus - Programming with C++

Function call by value

void swap(int x, int y) { int temp; temp = x; x = y; y = temp; return; }

Page 72: Esoft Metro Campus - Programming with C++

Function call by value #include <iostream> using namespace std;void swap(int x, int y);

int main () { int a = 100, b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0; }

Page 73: Esoft Metro Campus - Programming with C++

Function call by pointer

passing arguments to a function copies the address of an argument into the formal parameter.

Page 74: Esoft Metro Campus - Programming with C++

Function call by pointer

void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; return; }

Page 75: Esoft Metro Campus - Programming with C++

Function call by pointer#include <iostream> using namespace std;void swap(int *x, int *y); int main () { int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; swap(&a, &b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0; }

Page 76: Esoft Metro Campus - Programming with C++

Function call by reference

The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter.

Page 77: Esoft Metro Campus - Programming with C++

Function call by reference

void swap(int &x, int &y) { int temp; temp = x; x = y; y = temp; return; }

Page 78: Esoft Metro Campus - Programming with C++

Function call by reference#include <iostream> using namespace std;void swap(int &x, int &y); int main () { int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0; }

Page 79: Esoft Metro Campus - Programming with C++

Default Values for Parameters

• When you define a function, you can specify a default value for each.

• This value will be used if the corresponding argument is left blank when calling to the function.

Page 80: Esoft Metro Campus - Programming with C++

Default Values for Parameters#include <iostream>using namespace std;

void welcome(string name);

void welcome(string name = "Guest"){cout << "Welcome " << name << endl;}

int main(){welcome();welcome("Roshan");return 0;}

Page 81: Esoft Metro Campus - Programming with C++

Math Operations in C++

• C++ has a rich set of mathematical operations, which can be performed on various numbers.

• To utilize these functions you need to include the math header file <cmath>.

Page 82: Esoft Metro Campus - Programming with C++

Math Operations in C++

Page 83: Esoft Metro Campus - Programming with C++

Arrays

• An Array is a data structure which can store a fixed size sequential collection of elements of the same type.

• An array is used to store a collection of data.

Page 84: Esoft Metro Campus - Programming with C++

Single dimensional arrays

Page 85: Esoft Metro Campus - Programming with C++

Declaring Arrays

type arrayName [ arraySize ];

Ex:

double balance[10];

Page 86: Esoft Metro Campus - Programming with C++

Initializing Arrays

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

If you omit the size of the array, an array just big enough to hold the initialization is created.

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Page 87: Esoft Metro Campus - Programming with C++

Accessing Array Elements

An element is accessed by indexing the array name.

double salary = balance[0];

Page 88: Esoft Metro Campus - Programming with C++

Multi-dimensional Arrays

C++ programming language allows multidimensional arrays.

Here is the general form of a multidimensional array declaration:

type name[size1][size2]...[sizeN];

Page 89: Esoft Metro Campus - Programming with C++

Use of Multi-dimensional Arrays

Page 90: Esoft Metro Campus - Programming with C++

Two-Dimensional Arrays

Declaring a two dimensional array of size x, y

type arrayName [ x ][ y ];

Page 91: Esoft Metro Campus - Programming with C++

Initializing Two-Dimensional Arrays

int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} };

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Page 92: Esoft Metro Campus - Programming with C++

Accessing Two-Dimensional Array Elements

An element in two dimensional array is accessed by using row index and column index of the array.

int val = a[2][3];

Page 93: Esoft Metro Campus - Programming with C++

Passing Arrays as Function Arguments

Formal parameters as a pointervoid myFunction(int *param) { }

Formal parameters as a sized arrayvoid myFunction(int param[10]) { }

Formal parameters as an unsized arrayvoid myFunction(int param[]) { }

Page 94: Esoft Metro Campus - Programming with C++

Return array from function

int * myFunction() { static int demo[5] = {20, 40, 50, 10, 60}; return demo; }

Page 95: Esoft Metro Campus - Programming with C++

Pointer to an Array

double balance[5] = {20.50, 65.00, 35.75, 74.25, 60.00};double *ptr;ptr = balance;int i;

cout << "Array values using pointer" << endl;for(i=0; i<=4; i++){cout << "balance[" << i << "] =" << *(ptr+i) << endl;}

cout << "Array values using balance" << endl;for(i=0; i<=4; i++){cout << "balance[" << i << "] =" << *(balance+i) << endl;}

Page 96: Esoft Metro Campus - Programming with C++

Strings

C++ provides following two types of string representations:

• C-style character string. • string class type introduced with Standard C+

+.

Page 97: Esoft Metro Campus - Programming with C++

C-Style Character String

This string is actually a one-dimensional array of characters which is terminated by a null character '\0'

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

char greeting[] = "Hello"; // array initialization

Page 98: Esoft Metro Campus - Programming with C++

C-Style Character String

#include <iostream> using namespace std; int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << "Greeting message: "; cout << greeting << endl; return 0; }

Page 99: Esoft Metro Campus - Programming with C++

String functions in <cstring> header

Page 100: Esoft Metro Campus - Programming with C++

String Class in C++

The standard C++ library provides a string class type that supports all the operations mentioned above and additionally much more functionality.

Page 101: Esoft Metro Campus - Programming with C++

Copy Strings

string txt = "Hello"; // copy txt into str string str = txt;

Page 102: Esoft Metro Campus - Programming with C++

String Concatenation

string str1 = "Hello"; string str2 = "World"; string str3; // concatenates str1 and str2 str3 = str1 + str2; cout << "str1 + str2 : " << str3 << endl;

Page 103: Esoft Metro Campus - Programming with C++

String Length

string str = "Hello"; int len = str.size(); cout << "length of str: " << len << endl;

Page 104: Esoft Metro Campus - Programming with C++

Accessing Individual Elements

string my_string = "ten chars.";

for(int i = 0; i < my_string.length(); i++) { cout << my_string[i];}

Page 105: Esoft Metro Campus - Programming with C++

Find Strings

string txt = "hello world";int ret = txt.find("world");cout << "String found at: " << ret << endl;

Page 106: Esoft Metro Campus - Programming with C++

Substrings

string alphabet = "abcdefghijklmnop";string first_ten = alphabet.substr(0, 10);cout<<"The first ten letters are " << first_ten;

Page 107: Esoft Metro Campus - Programming with C++

Modifying Strings via Splicing or Erasure

string my_removal = "remove aaa";my_removal.erase(7, 3); // erases aaacout << my_removal << endl;

string my_string = "ade";my_string.insert(1, "bc");cout << my_string << endl;

Page 108: Esoft Metro Campus - Programming with C++

C++ Pointers

Some C++ tasks are performed more easily with pointers and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.

Page 109: Esoft Metro Campus - Programming with C++

Variable Address

every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator.

int n; char x[10];

cout << "Address of n variable: " << &n << endl; cout << "Address of x variable: " << &x << endl;

Page 110: Esoft Metro Campus - Programming with C++

What Are Pointers?

A pointer is a variable whose value is the address of another variable.

pointer variable declaration:

type *var-name;

Page 111: Esoft Metro Campus - Programming with C++

What Are Pointers?

Page 112: Esoft Metro Campus - Programming with C++

What Are Pointers?

int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to a character

Page 113: Esoft Metro Campus - Programming with C++

How to use Pointers?

1. Define a pointer variable.2. Assign the address of a variable to a pointer.3. Access the value at the address available in

the pointer variable.

Page 114: Esoft Metro Campus - Programming with C++

How to use Pointers?

int var = 20; int *ip; ip = &var;

cout << "Value of var variable: " << var << endl; cout << "Address stored in ip variable: " << ip << endl; cout << "Value of *ip variable: " << *ip << endl;

Page 115: Esoft Metro Campus - Programming with C++

NULL Pointers in C

int *ptr = NULL; cout << "The value of ptr is " << ptr ;

Page 116: Esoft Metro Campus - Programming with C++

Incrementing a Pointer

int var[] = {10, 100, 200}; int i, *ptr; ptr = var;

for ( i = 0; i <= 2; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr++; }

Page 117: Esoft Metro Campus - Programming with C++

Decrementing a Pointer

int var[] = {10, 100, 200}; int i, *ptr; ptr = &var[2];

for ( i = 2; i >= 0; i--) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr--; }

Page 118: Esoft Metro Campus - Programming with C++

Pointer Comparisons

int var[] = {10, 100, 200}; int i, *ptr; ptr = var; i = 0; while ( ptr <= &var[2] ) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr++; i++; }

Page 119: Esoft Metro Campus - Programming with C++

Array of pointers

int var[] = {10, 100, 200}; int i, *ptr[3];

for ( i = 0; i <= 2; i++) { ptr[i] = &var[i]; }

for ( i = 0; i < 2; i++) { cout << "Value of var[" << i << "] = "; cout << *ptr[i] << endl; }

Page 120: Esoft Metro Campus - Programming with C++

Pointer to Pointer

When we define a pointer to a pointer, the first pointer contains the address of the second

pointer.

Page 121: Esoft Metro Campus - Programming with C++

Pointer to Pointer

int var; int *ptr; int **pptr; var = 3000;ptr = &var;pptr = &ptr;cout << "Value of var :" << var << endl; cout << "Value available at *ptr :" << *ptr << endl; cout << "Value available at **pptr :" << **pptr << endl;

Page 122: Esoft Metro Campus - Programming with C++

Passing pointers to functions

void getSeconds(long *hours) { *hours = *hours * 60 * 60; }

int main () { long hours; getSeconds( &hours ); cout << "Number of seconds :" << hours << endl; return 0; }

Page 123: Esoft Metro Campus - Programming with C++

Return pointer from functionsint * getNumber( ) { static int r[5] = {20, 40, 50, 10, 60}; return r; }

int main () { int *p; int i; p = getNumber(); for ( i = 0; i <= 4; i++ ) { cout << "*(p + " << i << ") : "; cout << *(p + i) << endl; } return 0; }

Page 124: Esoft Metro Campus - Programming with C++

References

A reference variable is an alias, that is, another name for an already existing variable.

Page 125: Esoft Metro Campus - Programming with C++

C++ References vs Pointers

• You cannot have NULL references. • Once a reference is initialized to an object, it

cannot be changed to refer to another object. Pointer. Pointers can be pointed to another object at any time.

• A reference must be initialized when it is created. Pointers can be initialized at any time.

Page 126: Esoft Metro Campus - Programming with C++

Creating References in C++

int i = 17; int& r = i;

i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl;

Page 127: Esoft Metro Campus - Programming with C++

References as Parameters (Example)

void swap(int& x, int& y) { int temp; temp = x; x = y; y = temp; return; }

Page 128: Esoft Metro Campus - Programming with C++

References as Parameters (Example) #include <iostream> using namespace std;void swap(int& x, int& y); int main () { int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0; }

Page 129: Esoft Metro Campus - Programming with C++

Reference as Return Valuedouble vals[] = {10.1, 12.6, 33.1, 24.1, 50.0}; double& setValues( int i ) { return vals[i]; // return a reference to the ith element } int main () { setValues(1) = 20.23; // change 2nd element setValues(3) = 70.8; // change 4th element cout << "Value after change" << endl; for ( int i = 0; i <= 4; i++ ) { cout << "vals[" << i << "] = " << vals[i] << endl; } }

Page 130: Esoft Metro Campus - Programming with C++

Reference as Return Value

int& func() { int q; // return q; // Compile time error static int x; return x; // Safe, x lives outside this scope }

Page 131: Esoft Metro Campus - Programming with C++

Date and Time

• C++ inherits the structs and functions for date and time manipulation from C.

• To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program.

• There are four time-related types: clock_t, time_t, size_t, and tm.

Page 132: Esoft Metro Campus - Programming with C++

struct tm

struct tm { int tm_sec; // seconds of minutes from 0 to 61 int tm_min; // minutes of hour from 0 to 59 int tm_hour; // hours of day from 0 to 24 int tm_mday; // day of month from 1 to 31 int tm_mon; // month of year from 0 to 11 int tm_year; // year since 1900 int tm_wday; // days since sunday int tm_yday; // days since January 1st int tm_isdst; // hours of daylight savings time }

Page 133: Esoft Metro Campus - Programming with C++

Date and Time Functions

Page 134: Esoft Metro Campus - Programming with C++

Current date and time#include <iostream> #include <ctime> using namespace std; int main( ) { // current date/time based on current system time_t now = time(0); // convert now to string form char* dt = ctime(&now); cout << "The local date and time is: " << dt << endl; // convert now to tm struct for UTC tm *gmtm = gmtime(&now); dt = asctime(gmtm); cout << "The UTC date and time is:"<< dt << endl; }

Page 135: Esoft Metro Campus - Programming with C++

Format time using struct tm

#include <iostream> #include <ctime> using namespace std; int main( ) { // current date/time based on current system time_t now = time(0); cout << "Number of sec since January 1,1970:" << now << endl; tm *ltm = localtime(&now); // print various components of tm structure. cout << "Year: "<< 1900 + ltm->tm_year << endl; cout << "Month: "<< 1 + ltm->tm_mon<< endl; cout << "Day: "<< ltm->tm_mday << endl; cout << "Time: "<< 1 + ltm->tm_hour << ":"; cout << 1 + ltm->tm_min << ":"; cout << 1 + ltm->tm_sec << endl; }

Page 136: Esoft Metro Campus - Programming with C++

Structures

• Structure is another user defined data type which allows you to combine data items of different kinds.

• Structures are used to represent a record.

Page 137: Esoft Metro Campus - Programming with C++

Defining a Structure

struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables];

Page 138: Esoft Metro Campus - Programming with C++

Defining a Structure

struct Books { string title; string author; string category; int book_id; } book;

• You can specify one or more structure variables but it is optional.

• The structure tag is optional when there are structure variable definition.

Page 139: Esoft Metro Campus - Programming with C++

Assigning values to Structure

struct Books Book1; /* Declare Book1 of type Books */

Book1.title = "Tom Sawyer"; Book1.author = "Mark Twain"; Book1.category = "Novel"; Book1.book_id = 64954;

Page 140: Esoft Metro Campus - Programming with C++

Accessing Structure Members

cout << "Book 1 title : " << Book1.title << endl; cout << "Book 1 author : " << Book1.author << endl; cout << "Book 1 category : " << Book1.category << endl; cout << "Book 1 id : " << Book1.book_id << endl;

Page 141: Esoft Metro Campus - Programming with C++

Structures as Function Arguments

// function definitionvoid printBook( struct Books book ) { cout << "Book title : " << book.title <<endl; cout << "Book author : " << book.author <<endl; cout << "Book category : " << book.category <<endl; cout << "Book id : " << book.book_id <<endl;}

// calling functionprintBook( Book1 );

Page 142: Esoft Metro Campus - Programming with C++

Pointers to Structures

//define pointer to structurestruct Books *struct_pointer;

//store the address of a structure variable in the pointer struct_pointer = &Book1;

//access the members of a structurestruct_pointer->title;

Page 143: Esoft Metro Campus - Programming with C++

Basic Input / Output

• C++ I/O occurs in streams, which are sequences of bytes.

• If bytes flow from a device like a keyboard, a disk drive, or a network connection, etc to main memory, this is called input operation.

• If bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc this is called output operation.

Page 144: Esoft Metro Campus - Programming with C++

I/O Library Header Files

Page 145: Esoft Metro Campus - Programming with C++

The standard output stream (cout)

• The predefined object cout is an instance of ostream class.

• The cout object is said to be "connected to" the standard output device, which usually is the display screen.

Page 146: Esoft Metro Campus - Programming with C++

The standard output stream (cout)

#include <iostream> using namespace std; int main( ) { char str[] = "Hello C++"; cout << "Value of str is : " << str << endl;}

Page 147: Esoft Metro Campus - Programming with C++

The standard input stream (cin)

• The predefined object cin is an instance of istream class.

• The cin object is said to be attached to the standard input device, which usually is the keyboard.

Page 148: Esoft Metro Campus - Programming with C++

The standard input stream (cin)

#include <iostream> using namespace std; int main( ) { char name[50]; cout << "Please enter your name: "; cin >> name; cout << "Your name is: " << name << endl; }

Page 149: Esoft Metro Campus - Programming with C++

The standard error stream (cerr)

• The predefined object cerr is an instance of ostream class.

• The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately.

Page 150: Esoft Metro Campus - Programming with C++

The standard error stream (cerr)

#include <iostream> using namespace std; int main( ) { char str[] = "Unable to read...."; cerr << "Error message : " << str << endl; }

Page 151: Esoft Metro Campus - Programming with C++

The standard log stream (clog)

• The predefined object clog is an instance of ostream class.

• The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered.

• This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.

Page 152: Esoft Metro Campus - Programming with C++

The standard log stream (clog)

#include <iostream> using namespace std; int main( ) { char str[] = "Unable to read...."; clog << "Error message : " << str << endl; }

Page 153: Esoft Metro Campus - Programming with C++

Classes and Objects

• The main purpose of C++ programming is to add object orientation to the C programming language.

• A class is used to specify the form of an object and it combines data representation and methods.

Page 154: Esoft Metro Campus - Programming with C++

C++ Class Definitions

• When you define a class, you define a blueprint for a data type.

• It define what data an object will consist of and what operations it can be performed.

Page 155: Esoft Metro Campus - Programming with C++

C++ Class Definitions

class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };

Page 156: Esoft Metro Campus - Programming with C++

Define C++ Objects

Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box

Page 157: Esoft Metro Campus - Programming with C++

Accessing the Data Members // box 1 specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0;

// volume of box 1 volume = Box1.height * Box1.length * Box1.breadth; cout << "Volume of Box1 : " << volume << endl; // volume of box 2 volume = Box2.height * Box2.length * Box2.breadth; cout << "Volume of Box2 : " << volume << endl;

Page 158: Esoft Metro Campus - Programming with C++

Class Member Functions

class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void) { return length * breadth * height; } };

Page 159: Esoft Metro Campus - Programming with C++

Scope resolution operatoryou can define same function outside the class using scope resolution operator ::

class Box { public: double length; double breadth; double height; double getVolume(void); // Returns box volume };

double Box::getVolume(void) { return length * breadth * height; }

Page 160: Esoft Metro Campus - Programming with C++

Class Access Modifiers

The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body.

Page 161: Esoft Metro Campus - Programming with C++

Class Access Modifiersclass Base { public: // public members go here protected: // protected members go here private: // private members go here };

Page 162: Esoft Metro Campus - Programming with C++

Class Access Modifiers

• Public members: – Accessible from anywhere outside the class but

within a program.• Private members: – Cannot be accessed, or even viewed from outside

the class.• Protected members: – Similar to a private member but they can be

accessed in child classes.

Page 163: Esoft Metro Campus - Programming with C++

Class Constructor

• A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

• A constructor will have exact same name as the class and it does not have any return type.

• Constructors can be very useful for setting initial values for certain member variables.

Page 164: Esoft Metro Campus - Programming with C++

Class Constructor#include <iostream> using namespace std;

class Line { public: Line(); // This is the constructor };

Line::Line(void) { cout << "Object is being created" << endl; }

int main( ) { Line line; // creates an object, invokes constructor return 0; }

Page 165: Esoft Metro Campus - Programming with C++

Parameterized Constructor#include <iostream> using namespace std; class Line { public: Line(double len); // This is the constructor double length; }; Line::Line( double len) { cout << "Object is being created, length = " << len << endl; length = len; } int main( ) { Line line(10.0); cout << "Length of line : " << line.length << endl; return 0; }

Page 166: Esoft Metro Campus - Programming with C++

Using Initialization Lists

// In case of parameterized constructor, you can use following syntax to initialize the fields

Line::Line( double len) { cout << "Object is being created, length = " << len << endl; length = len; }

// Following syntax is equal to the above syntax:

Line::Line( double len): length(len) { cout << "Object is being created, length = " << len << endl; }

Page 167: Esoft Metro Campus - Programming with C++

Class Destructor

• A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

• Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

Page 168: Esoft Metro Campus - Programming with C++

Class Destructor#include <iostream> using namespace std; class Line { public: Line(); // This is the constructor declaration ~Line(); // This is the destructor declaration double length; }; Line::Line(void) { cout << "Object is being created" << endl; }

Line::~Line(void) { cout << "Object is being deleted" << endl; } int main( ) { Line line; line.length = 6.0; cout << "Length of line : " << line.length << endl; return 0; }

Page 169: Esoft Metro Campus - Programming with C++

Copy Constructor

• A copy constructor is a special constructor for creating a new object as a copy of an existing object.

• The copy constructor is used to: – Initialize one object from another of the same type. – Copy an object to pass it as an argument to a

function. – Copy an object to return it from a function.

Page 170: Esoft Metro Campus - Programming with C++

Copy Constructor#include <iostream>using namespace std;

class Student{public:string name;//constructorStudent(string n){name = n;cout << "Constructor invoked, name: " << name << endl;}

//copy constructorStudent(Student &s){name = "copy of " + s.name;cout << "Copy constructor invoked, name: " << name << endl;}};

//create a copy of its argumentvoid testfunc(Student arg){ cout << "Hello from testfunc" << endl;}

int main(){Student x("Roshan"); //invokes constructortestfunc(x); //invokes copy constructor return 0;}

Page 171: Esoft Metro Campus - Programming with C++

C++ Friend Functions

• A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class.

• Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

Page 172: Esoft Metro Campus - Programming with C++

C++ Friend Functions #include <iostream> using namespace std; class Box { double width; public: friend void printWidth( Box box ); void setWidth( double wid ); }; void Box::setWidth( double wid ) { width = wid; } void printWidth( Box box ) { cout << "Width of box : " << box.width <<endl; }

int main( ) { Box box; box.setWidth(10.0); printWidth( box ); return 0; }

Page 173: Esoft Metro Campus - Programming with C++

The this Pointer in C++

• Every object in C++ has access to its own address through an important pointer called this pointer.

• this pointer is an implicit parameter to all member functions.

Page 174: Esoft Metro Campus - Programming with C++

The this Pointer in C++ #include <iostream> using namespace std; class Box { public: Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume(); } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; }else{ cout << "Box2 is equal to or larger than Box1" <<endl; } return 0; }

Page 175: Esoft Metro Campus - Programming with C++

Pointer to C++ Classes#include <iostream> using namespace std; class Box{ public: Box(double l=2.0, double b=2.0, double h=2.0){ cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void){ Box Box1(3.3, 1.2, 1.5); // Declare box1 Box *ptrBox; // Declare pointer to a class. ptrBox = &Box1; cout << "Volume of Box1: " << ptrBox->Volume() << endl; return 0; }

Page 176: Esoft Metro Campus - Programming with C++

Static Members of a Class

• When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

• A static member is shared by all objects of the class.

Page 177: Esoft Metro Campus - Programming with C++

Static Members of a Class#include <iostream> using namespace std; class Box{ public: static int objectCount; Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; objectCount++; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int Box::objectCount = 0;

int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 cout << "Total objects: " << Box::objectCount << endl; return 0; }

Page 178: Esoft Metro Campus - Programming with C++

Static Function Members

• A static member function can be called even if no objects of the class exist.

• Static functions are accessed using only the class name and the scope resolution operator ::.

• A static member function can only access static data member, other static member functions and any other functions from outside the class.

Page 179: Esoft Metro Campus - Programming with C++

Static Function Members#include <iostream> using namespace std; class Box{ public: static int objectCount; Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; objectCount++; } static int getCount() { return objectCount; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int Box::objectCount = 0; int main(void){ cout << "Inital Stage Count: " << Box::getCount() << endl; Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 cout << "Final Stage Count: " << Box::getCount() << endl; return 0; }

Page 180: Esoft Metro Campus - Programming with C++

Inheritance

• Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application.

• The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Page 181: Esoft Metro Campus - Programming with C++

Base & Derived Classes

• A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes.

• A class derivation list names one or more base classes and has the form:

class derived-class: access-specifier base-class

Page 182: Esoft Metro Campus - Programming with C++

Base class “Shape” (continued)

#include <iostream> using namespace std; class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; };

Page 183: Esoft Metro Campus - Programming with C++

Derived class “Rectangle” (continued)

class Rectangle: public Shape { public: int getArea() { return (width * height); } };

Page 184: Esoft Metro Campus - Programming with C++

Main function

int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; return 0; }

Page 185: Esoft Metro Campus - Programming with C++

Access Control and Inheritance

Page 186: Esoft Metro Campus - Programming with C++

Type of Inheritance• Public Inheritance:

– Public members of the base class become public members of the derived class.

– Protected members of the base class become protected members of the derived class.

– Base class's private members are never accessible directly from a derived class.

• Protected Inheritance:– Public and protected members of the base class become protected

members of the derived class.

• Private Inheritance:– Public and protected members of the base class become private

members of the derived class.

Page 187: Esoft Metro Campus - Programming with C++

Multiple Inheritances

• A C++ class can inherit members from more than one class

• Here is the extended syntax:

class derived-class: access baseA, access baseB....

Page 188: Esoft Metro Campus - Programming with C++

Base class Shape #include <iostream> using namespace std; class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; };

Page 189: Esoft Metro Campus - Programming with C++

Base class PaintCost

class PaintCost { public: int getCost(int area) { return area * 70; } };

Page 190: Esoft Metro Campus - Programming with C++

Derived class

class Rectangle: public Shape, public PaintCost { public: int getArea() { return (width * height); } };

Page 191: Esoft Metro Campus - Programming with C++

Main function int main(void) { Rectangle Rect; int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; // Print the total cost of painting cout << "Total paint cost: $" << Rect.getCost(area) << endl; return 0; }

Page 192: Esoft Metro Campus - Programming with C++

Overloading

C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.

Page 193: Esoft Metro Campus - Programming with C++

Function overloading#include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void){ printData pd; pd.print(5); // Call print to print integer pd.print(500.263); // Call print to print float pd.print("Hello C++"); // Call print to print character return 0; }

Page 194: Esoft Metro Campus - Programming with C++

Operators overloading

• You can redefine or overload most of the built-in operators available in C++. Thus a programmer can use operators with user-defined types as well.

• Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.

• Like any other function, an overloaded operator has a return type and a parameter list.

Page 195: Esoft Metro Campus - Programming with C++

Binary Operators overloading#include <iostream> using namespace std; class Line{public:int length;

Line operator+ (Line l){Line new_line;new_line.length = this->length + l.length;return new_line;}

};

int main(){Line x, y, z;x.length = 35;cout << "Length of x: " << x.length << endl;y.length = 65;cout << "Length of y: " << y.length << endl;z = x + y;cout << "Length of z: " << z.length << endl;return 0;}

Page 196: Esoft Metro Campus - Programming with C++

Unary Operators Overloading#include <iostream> using namespace std; class Distance{public:int feets;int inches;

Distance(int f, int i){feets = f;inches = i;}

Distance operator- (){feets = -feets;inches = -inches;return Distance(feets, inches);}

};

int main(){Distance x(40, 5);-x;cout << "Feets of x: " << x.feets << endl;cout << "Inches of x: " << x.inches << endl;return 0;}

Page 197: Esoft Metro Campus - Programming with C++

Comparison Operators Overloading#include <iostream> using namespace std; class Distance{public:int feets;int inches;Distance(int f, int i){feets = f;inches = i;}bool operator> (const Distance &d){if(feets > d.feets){return true;}else if(feets == d.feets && inches > d.inches){return true;}else{return false;}}};

int main(){Distance x(40, 5);Distance y(40, 6);if(x > y){cout << "x is larger than y"<< endl;}else{cout << "x is not larger than y"<< endl;}return 0;}

Page 198: Esoft Metro Campus - Programming with C++

Assignment Operators Overloading#include <iostream> using namespace std; class Distance{

public:int feets;int inches;

Distance(int f, int i){feets = f;inches = i;}

void operator= (const Distance &d){feets = d.feets;inches = d.inches;}

};

int main(){Distance x(40, 5);Distance y(30, 6);x = y;cout << "Distance of x, Feets: " << x.feets << " Inches: " << x.inches;return 0;}

Page 199: Esoft Metro Campus - Programming with C++

Polymorphism

• The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

• C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

Page 200: Esoft Metro Campus - Programming with C++

Polymorphism (continued)#include <iostream> using namespace std; class Shape { protected: int width, height; public: virtual void area() { cout << "Parent class area :" <<endl; } };

class Rectangle: public Shape{ public: Rectangle( int a=0, int b=0) { width = a; height = b; } void area () {

int ans = width * height; cout << "Rectangle class area :" << ans << endl; } };

Page 201: Esoft Metro Campus - Programming with C++

Polymorphismclass Triangle: public Shape { public: Triangle( int a=0, int b=0){

width = a; height = b; } void area () { cout << "Triangle class area :" << (width * height / 2) << endl; } };

int main( ) { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); shape = &rec; shape->area(); shape = &tri; shape->area(); return 0; }

Page 202: Esoft Metro Campus - Programming with C++

Interfaces

• An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class.

• The C++ interfaces are implemented using abstract classes.

• A class is made abstract by declaring at least one of its functions as pure virtual function.

Page 203: Esoft Metro Campus - Programming with C++

Interfaces

class Box { public: // pure virtaul function virtual double getVolume() = 0; private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };

Page 204: Esoft Metro Campus - Programming with C++

Interfaces

• purpose of an abstract class is to provide an appropriate base class from which other classes can inherit.

• Abstract classes cannot be used to instantiate objects and serves only as an interface.

• Classes that can be used to instantiate objects are called concrete classes.

Page 205: Esoft Metro Campus - Programming with C++

Files and Streams

To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.

Page 206: Esoft Metro Campus - Programming with C++

Opening a File

Following is the standard syntax for open() function

void open(const char *filename, ios::openmode mode);

Page 207: Esoft Metro Campus - Programming with C++

Opening a File

Page 208: Esoft Metro Campus - Programming with C++

Closing a File

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

void close();

Page 209: Esoft Metro Campus - Programming with C++

Writing to a File#include <fstream>#include <iostream>using namespace std;

int main(){char data[100];ofstream outfile;outfile.open("afile.dat"); // open a file in write mode. cout << "enter your name: ";cin.getline(data, 100);outfile << data << endl; // write inputted data into the file. cout << "Enter your age: ";cin >> data; // again write inputted data into the file. cin.ignore();outfile << data << endl;outfile.close(); // close the opened file. return 0;}

Page 210: Esoft Metro Campus - Programming with C++

Reading from a File#include <fstream>#include <iostream>using namespace std;

int main(){char data[100];ifstream infile; //open a file in read modeinfile.open("afile.dat");cout << "reading from the file" << endl;infile >> data;cout << data << endl; //write data on screeninfile >> data; // again read filecout << data << endl;infile.close(); //close filereturn 0;}

Page 211: Esoft Metro Campus - Programming with C++

Exception Handling

• An exception is a problem that arises during the execution of a program.

• A C++ exception is a response to an exceptional circumstance that arises while a program is running

Page 212: Esoft Metro Campus - Programming with C++

Exception Handling

C++ exception handling is built upon three keywords: try, catch, and throw.

• throw: A program throws an exception when a problem shows up.

• try: Identifies a block of code for which particular exceptions will be activated.

• catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem.

Page 213: Esoft Metro Campus - Programming with C++

The try catch blocks

try { // protected code }catch( ExceptionName e1 ) { // catch block }catch( ExceptionName e2 ) { // catch block }catch( ExceptionName eN ) { // catch block }

Page 214: Esoft Metro Campus - Programming with C++

Throwing Exceptions

double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); }

Page 215: Esoft Metro Campus - Programming with C++

Catching Exceptions

try { // protected code }catch( ExceptionName e ) { // code to handle ExceptionName exception }

try { // protected code }catch(...) { // code to handle any exception }

Page 216: Esoft Metro Campus - Programming with C++

Catching Exceptionsdouble division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; }catch (const char* msg) { cerr << msg << endl; } return 0; }

Page 217: Esoft Metro Campus - Programming with C++

C++ Standard Exceptions

Page 218: Esoft Metro Campus - Programming with C++

C++ Standard Exceptions

Page 219: Esoft Metro Campus - Programming with C++

Define New Exceptions#include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; int main() { try { throw MyException(); } catch(MyException& e) { std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { //Other errors } }

Page 220: Esoft Metro Campus - Programming with C++

Dynamic Memory

Memory in your C++ program is divided into two parts:

• The stack: All variables declared inside the function will take up memory from the stack.

• The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs.

Page 221: Esoft Metro Campus - Programming with C++

The new and delete operators

Syntax to use new operator to allocate memory dynamically for any data-type

new data-type;

Free up the memory that it occupies

delete pvalue;

Page 222: Esoft Metro Campus - Programming with C++

Dynamic Memory Allocation

#include <iostream> using namespace std; int main () { double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable *pvalue = 29494.99; // Store value at allocated address cout << "Value of pvalue : " << *pvalue << endl; delete pvalue; // free up the memory. return 0; }

Page 223: Esoft Metro Campus - Programming with C++

Dynamic Memory Allocation for Arrays

char* pvalue = NULL; // Pointer initialized with null pvalue = new char[20]; // Request memory for the variable delete [] pvalue; // Delete array pointed to by pvalue

double** pvalue = NULL; // Pointer initialized with null pvalue = new double [3][4]; // Allocate memory for a 3x4 array delete [] pvalue; // Delete array pointed to by pvalue

Page 224: Esoft Metro Campus - Programming with C++

Dynamic Memory Allocation for Objects#include <iostream> using namespace std;

class Box { public: Box() { cout << "Constructor called!" <<endl; } ~Box() { cout << "Destructor called!" <<endl; } }; int main( ) { Box* myBoxArray = new Box[4]; delete [] myBoxArray; // Delete array return 0; }

Page 225: Esoft Metro Campus - Programming with C++

Namespaces

• Using namespace, you can define the context in which names are defined.

• In essence, a namespace defines a scope.

Page 226: Esoft Metro Campus - Programming with C++

Defining a Namespace

namespace namespace_name { // code declarations }

// To call the namespace-enabled version of either function or variable

name::code; // code could be variable or function.

Page 227: Esoft Metro Campus - Programming with C++

Defining a Namespace#include <iostream> using namespace std; // first name space namespace first_space{ void func(){ cout << "Inside first_space" << endl; } } // second name space namespace second_space{ void func(){ cout << "Inside second_space" << endl; } }

int main () { first_space::func(); // Calls function from first name space. second_space::func(); // Calls function from second name space. return 0; }

Page 228: Esoft Metro Campus - Programming with C++

The using directive

This directive tells the compiler that the subsequent code is making use of names in the specified namespace.

Page 229: Esoft Metro Campus - Programming with C++

The using directive#include <iostream> using namespace std; // first name space namespace first_space { void func(){ cout << "Inside first_space" << endl; } } // second name space namespace second_space { void func(){ cout << "Inside second_space" << endl; } }

using namespace first_space; int main () { func(); // This calls function from first name space. return 0; }

Page 230: Esoft Metro Campus - Programming with C++

The using directive

#include <iostream>

//using directive can also be used to refer to a particular item within a namespace

using std::cout;

int main () { cout << "std::endl is used with std!" << std::endl; return 0; }

Page 231: Esoft Metro Campus - Programming with C++

Nested Namespaces

namespace namespace_name1 {

// code declarations namespace namespace_name2 { // code declarations }

}

// to access members of namespace_name2 using namespace namespace_name1::namespace_name2;

Page 232: Esoft Metro Campus - Programming with C++

Templates

• Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types.

• This allows a function or class to work on many different data types without being rewritten for each one.

Page 233: Esoft Metro Campus - Programming with C++

Function Templates

A function template behaves like a function except that the template can have arguments of many different types.

Syntax:

template <class identifier> function_declaration;

template <typename identifier> function_declaration;

Page 234: Esoft Metro Campus - Programming with C++

Function Templates#include <iostream>using namespace std;

template<class TYPE>void PrintTwice(TYPE data){ cout<< "Twice: " << data * 2 << endl;}

template<class TYPE>TYPE Twice(TYPE data){ return data * 2;}

int main(){PrintTwice(4);PrintTwice(5.3);cout << "Twice: " << Twice(7) << endl;cout << "Twice: " << Twice(7.6) << endl;return 0;}

Page 235: Esoft Metro Campus - Programming with C++

Class Templates

A class template provides a specification for generating classes based on parameters.

Syntax: template <class type> class class-name {

}

You can define more than one generic data type by using a comma separated list.

Page 236: Esoft Metro Campus - Programming with C++

Class Templatestemplate<class T>class Item{ T Data; public: Item() : Data( T() ) //constructor initializes Data to 0 {}

void SetData(T nValue){ Data = nValue; } void PrintData(){ cout << Data << endl; }};

int main(){Item<int> x;x.SetData(10);x.PrintData();

Item<float> y;y.SetData(5.6);y.PrintData();return 0;}

Page 237: Esoft Metro Campus - Programming with C++

Preprocessor

• The preprocessors are the directives which give instruction to the compiler to preprocess the information before actual compilation starts.

• Preprocessor directives are not C++ statements, so they do not end in a semicolon.

Page 238: Esoft Metro Campus - Programming with C++

The #define Preprocessor

#define MAX_ARRAY_LENGTH 20

Tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.

Page 239: Esoft Metro Campus - Programming with C++

The #undef Preprocessor

#undef FILE_SIZE #define FILE_SIZE 42

Tells the CPP to undefine existing FILE_SIZE and define it as 42

Page 240: Esoft Metro Campus - Programming with C++

Function Like Macros

#include <iostream> using namespace std; #define MIN(a, b) (a<b ? a : b) int main () { int i, j; i = 100; j = 30; cout <<"The minimum is " << MIN(i, j) << endl; return 0; }

Page 241: Esoft Metro Campus - Programming with C++

The #include Preprocessor

#include <stdio.h> #include "myheader.h"

Tell the CPP to get stdio.h from System Libraries and add the text to the current source file.

The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.

Page 242: Esoft Metro Campus - Programming with C++

Conditional Compilation

#ifndef MESSAGE #define MESSAGE "You wish!" #endif

Tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

Page 243: Esoft Metro Campus - Programming with C++

Conditional Compilation

#define BOO

#ifdef BOO cout << "Your debugging statement" << endl;#endif

Tells the CPP to do the process the statements enclosed if BOO is defined.

Page 244: Esoft Metro Campus - Programming with C++

Conditional Compilation

#if 0 code prevented from compiling #endif

Page 245: Esoft Metro Campus - Programming with C++

The # Operator#include <iostream> using namespace std;

//creates a text token x to be converted to a string surrounded by quotes.

#define MYTXT(x) #x int main () { cout << MYTXT(Hello world) << endl; // cout << "Hello world" << endl;return 0; }

Page 246: Esoft Metro Campus - Programming with C++

The ## Operator#include <iostream> using namespace std;

// arguments are concatenated and used to replace the macro.#define MYCONCAT(x, y) x ## y int main () { int xy = 100;cout << MYCONCAT(x, y) << endl; //cout << xy << endl;return 0; }

Page 247: Esoft Metro Campus - Programming with C++

Predefined C++ Macros

Page 248: Esoft Metro Campus - Programming with C++

Multitasking

There are two types of multitasking:

• Process based– Process based multitasking handles the concurrent

execution of programs.

• Thread based. – Thread based multitasking deals with the concurrent

execution of pieces of the same program.

Page 249: Esoft Metro Campus - Programming with C++

Multithreading

• Multithreading is a multitasking feature that allows your computer to run two or more programs concurrently.

• A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread.

Page 250: Esoft Metro Campus - Programming with C++

Creating Threads

There is following routine which we use to create a thread:

#include <pthread.h>

pthread_create (thread, attr, start_routine, arg)

Page 251: Esoft Metro Campus - Programming with C++

pthread_create parameters

Page 252: Esoft Metro Campus - Programming with C++

Terminating Threads

There is following routine which we use to terminate a thread:

#include <pthread.h>

pthread_exit (status)

Page 253: Esoft Metro Campus - Programming with C++

Creating Threads#include <iostream>#include <pthread.h>using namespace std;

void *t_func(void *arg){ cout << "Hello from t_func()\n"; pthread_exit(NULL);}

int main(){ pthread_t t1;

cout << "In main: creating a thread\n"; int ret = pthread_create(&t1, NULL, &t_func, NULL); if(ret != 0) { cout << "Thread creation failed\n"; exit(EXIT_FAILURE); } pthread_exit(NULL);}

Page 254: Esoft Metro Campus - Programming with C++

Passing arguments to threads#include <iostream>#include <pthread.h>using namespace std;

void *t_func(void *arg){ for(int i=1; i<=9; i++){ cout << "Hello from t_func():" << (int) arg*i << endl; } pthread_exit(NULL);}

int main(){pthread_t t[2];int targ[] = {1, 10};for(int i=0; i<=1; i++){ cout << "In main: creating a thread\n"; int ret = pthread_create(&t[i], NULL, &t_func, (void *) targ[i]); if(ret != 0) cout << "Thread creation failed\n";}cout << "In main: end of main()\n";pthread_exit(NULL);}

Page 255: Esoft Metro Campus - Programming with C++

Joining Threads

There are following two routines which we can use to join or detach threads:

pthread_join (threadid, status)

The pthread_join() subroutine blocks the calling thread until the specified thread terminates.

Page 256: Esoft Metro Campus - Programming with C++

Joining Threads#include <iostream>#include <pthread.h>using namespace std;

void *t_func(void *arg){ for(int i=1; i<=9; i++){ cout << "Hello from t_func():" << (int) arg*i << endl; } pthread_exit(NULL);}

int main(){ pthread_t t[2]; int targ[] = {1, 10}; void *ret_join; for(int i=0; i<=1; i++){ cout << "In main: creating a thread\n"; int ret = pthread_create(&t[i], NULL, &t_func, (void *) targ[i]); if(ret != 0) cout << "Thread creation failed\n"; ret = pthread_join(t[i], &ret_join); //wait until t[i] completes if(ret != 0) cout << "Thread join failed\n"; cout << "Thread joined, it returned " << ret_join << endl ; } cout << "In main: end of main()\n"; pthread_exit(NULL);}

Page 257: Esoft Metro Campus - Programming with C++

The End

http://twitter.com/rasansmn