Programming in C++ - 195.01.03
Programming in C++ - 195.01.03
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 195.01.03
1
Table of Contents
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 2
C++ Programming
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 3
Features of C++
• Object-oriented programming
• Portability
• Modular programming
• C Compatibility
• Speed
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 4
Module 1: Getting Started
• Overview
First C++ program
Standard O/P and I/P in C++
Data types and Modifiers
Variables and Constants
Operators
Loops and Conditions
Type Conversions
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 5
The first C++ program
• /* First.cpp */
• #include <iostream>
• using namespace std;
• int main( )
• {
• cout<<"Hello! This is my first C++ program\n";
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 6
The first C++ program contd…
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 7
Standard Output
Consider the statements
cout<<“value of var1is :”;
int var1=14;
cout<< var1;
cout<<“The addition of ”<<a<<“and”<<b<<is<<a+b.;
Syntax:
cout<<“string”;
cout<<variable;
cout<<cascade1<<cascade2;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 8
Standard Input
Syntax:
cin>>variable1;
cin>>cascade1>>cascade2;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 9
Data types
• Modifiers
signed , unsigned
short, long
void
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 10
Data Type Modifiers
TYPE SIZE (Bytes) for SIZE (Bytes) for
TC++ Windows/ Unix
char or signed char 1 1
unsigned char 1 1
int or signed int 2 4
unsigned int 2 4
short int or signed 2 2
short int
unsigned short int 2 2
long int or signed long 4 4
int
unsigned long int 4 4
float 4 4
double 8 8
long double 10 10
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 11
Variables & Constants
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 12
Variables
Naming rules:
6. The first character must be a letter or an underscore
7. Subsequent characters must be either letters, digits, or
underscores.
8. Keywords , white spaces, punctuation marks or symbols
not allowed
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 13
Declaring variables
Example:
int x, y, z;
char name=‘G’;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 14
The ‘sizeof’ operator
Syntax:
sizeof (datatype);
sizeof variableName;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 15
The Constants
Types:
integer, character, string, float.
Integer Constants
Integers are whole numbers.
Default is decimal.
Octal numbers preceded by a ‘ 0 ’.
Hexadecimal numbers are preceded by a ‘ 0x ’.
Long integers specified using ‘ l ’ after an integer
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 16
The Constants contd…
Character Constants:
A single character is enclosed in single quotes.
Some Escape sequence character constants:
'\n' new line
'\t' horizontal tab
'\r' carriage return
'\b' backspace
'\a' alert
'\\' backslash
'\’' apostrophe
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 17
The Constants contd…
String Constants :
Sequence of characters enclosed in double quotes.
A null terminated character automatically placed at the end of
each string .
Float Constants:
Used to represent floating numbers
Consist of an integer part, a decimal point and a fraction part.
Scientific notation can also be used.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 18
The Constants contd…
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 20
The Symbolic Constants
1. #define TEN 10
2. #define RNUM 28.5
3. #define CHARACTER 'C'
4. #define STRING "This is a constant string."
5. int main ( ){
6. int num1 = TEN;
7. double num2 = RNUM;
8. char c = CHARACTER;
9. cout<<STRING;
10. cout<<"\nThe value of num1="<<num1;
11. cout<<"\nThe value of num2="<<num2;
12. cout<<"\nThe character c is "<<c<<"which has an ASCII
code of"<<(int)c;
13. cout<<"\n10 in decimal is equal to "<<oct<<TEN<<"in
octal and" <<hex<<TEN<<" in hex ";
14. return 0;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 21
The Constant Variables
Syntax:
const datatype
variable_name=value;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 22
The Operators
Types:
Arithmetic : + - ++ -- + - * / %
Assignment : = , += -= *= /= %=
Relational : > < >= <= == !=
Logical : && || !
Bitwise : & | ^ << >> ~
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 23
Increment and Decrement Operators
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 24
Special Assignment Operators
The expression
i = i + 5;
can also be written as
i += 5; /* Add 5 to i */
Similarly,
i -= 5; /* Subtract 5 from i */
i *= 5; /* Multiply i with 5 */
i /= 5; /* Divide i by 5 */
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 25
Fahrenheit to Celsius conversion
1. #include<iostream>
2. using namespace std;
4. int main( )
5. {
6. int fahr=100, celsius;
7. celsius= 5*(fahr-32)/9;
8. cout<<fahr<<" Fahrenheit = "<<celsius<<" Celsius";
9. cout<<endl;
10. return 0;
11. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 26
Logical operators
1. int main ( ){
2. float f1, f2;
3. cout << "Enter a floating point number (f1)" << endl;
4. cin >> f1;
5. cout << "Enter another floating point number (f2)"
<< endl;
6. cin >> f2;
7. cout << "f1 > f2 is " << (f1 > f2) << endl;
8. cout << "f1 < f2 is " << (f1 < f2) << endl;
9. cout << "f1 == f2 is " << (f1 == f2) << endl;
10. cout << "f1 != f2 is " << (f1 != f2) << endl;
11. cout << "f1 >= f2 is " << (f1 >= f2) << endl;
12. cout << "f1 <= f2 is " << (f1 <= f2) << endl;
13. cout << "f1 && f2 is " << (f1 && f2) << endl;
14. cout << "f1 || f2 is " << (f1 || f2) << endl;
15.
Pragati }Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Software Pvt. 27
Loops and Conditions
• Overview
Selection
if statement
switch statement
Iteration
while
do while
for
Control flow transfer statements
break
continue
goto
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 28
Selection Statements
• Selection
The if statement
The switch statement
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 29
The if statement
Start
True If
Statement1
condition
Statement
End
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 30
The if…else statement
Start
False
True If
Statement1 Statement2
condition
Statement3
End
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 31
if construct
if (i==3) cout<<“Hattrick!!”;
if ( year_of_service>3) bonus=2500;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 32
if construct -- different forms
if(condition) if(condition)
Statement {
Statements
}
if(condition)
if(condition) {
Statement
else Statements
Statement }
else
{
Statements
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 33
if else contd…
if(condition)
{
if(condition)
Statement
else
Statement
}
else
{
if(condition)
Statement
else
Statement
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 34
The if…else if ladder
if(condition)
{
Statement
}
else if(condition)
{
Statement
}
else if(condition)
{
Statement
}
else
{
Statement
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 35
Conditional Operator
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 36
Program to find vowel
1. int main( )
2. {
3. char ch;
4. cout<<"\nEnter any character : "; cin>>ch;
5. if(ch=='a') cout<<"\n"<<ch<<" is a vowel";
6. else if (ch=='e')
7. cout<<"\n"<<ch<<" is a vowel";
8. else if (ch=='i')
9. cout<<"\n"<<ch<<" is a vowel";
10. else if (ch=='o')
11. cout<<"\n"<<ch<<" is a vowel";
12. else if (ch=='u')
13. cout<<"\n"<<ch<<" is a vowel";
14. else
15. cout<<"\n"<<ch<<" is a consonent";
16. return 0;
17. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 37
Using the || operator
1. int main( )
2. {
3. char ch;
4. cout<<"\nEnter any character : ";
5. cin>>ch;
6. if(ch=='a' ||ch=='e' || ch=='i'|| ch=='o' || ch=='u')
7. cout<<ch<<" is a vowel"<<endl;
8. else
9. cout<<ch<<" is a consonent"<<endl;
10. return 0;
11. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 38
The nested if-else
1. int main ( )
2. {
3. int a=4,b=4; char ch;
4. cout<<"Enter which operation u wish to perform";
cin>>ch;
5. if (ch == '+') a += b;
6. else if (ch == '-') a -= b;
7. else if (ch == '*') a *= b;
8. else if (ch == '/') a/=b;
9. else{
10. cout<<"Error";
11. return 1;
12. }
13. cout<<"Result is :"<<a<<endl;
14. return 0;
15. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 39
The switch statement
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 40
Using the switch-case
The example for nested-if can be modified using switch- case as
follows:
switch (ch){
case '+' :
a += b; break;
case '-' :
a -= b; break;
case '*' :
a *= b; break;
case '/' :
a /= b; break;
default :
cout<<"error";
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 41
Program to find vowel using switch-case
• int main( ){
• char ch;
• cout<<"\nEnter any character : "; cin>>ch;
• switch(ch)
• {
• case 'a':
• case 'e':
• case 'i':
• case 'o':
• case 'u':
• cout<<ch<<" is a vowel"<<endl;
• break;
• default: cout<<ch<<" is a consonent"<<endl;
• }
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 42
Iteration
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 43
The while loop
Start
false
while
Exit loop
condition
true
statements End
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 44
The while loop
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 45
Using while
• #include <iostream>
• using namespace std;
• int main( )
• {
• int i;
• i=1;
• while(i<=10)
• {
• cout<<“\nValue of i is :”<<i;
• i = i + 1;
• }
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 46
Using while Contd…
1. #include <iostream>
2. using namespace std;
3. int main( )
4. {
5. int num;
6. char another='y';
7. while(another=='y') {
8. cout<<"Enter a number ";
9. cin>>num;
10. cout<<"square of "<<num<<" = "
<<num*num;
11. cout<<"\n What to enter another number ??
y/n:";
12. cin>>another;
13. }
14. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 47
The do - while loop
Start
statements
while
Exit loop
condition false
true
End
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 48
The do - while loop Contd…
Syntax:
do do{
statement1;
statement; statement2;
while } while
(expression); (expression);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 49
Using do-while
1. #include <iostream>
2. using namespace std;
3. int main( )
4. {
5. int i;
6. i=1;
7. do
8. {
9. cout<<"\nValue of i is : "<<i;
10. i = i + 1;
11. } while (i<=10);
12. return 0;
13. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 50
The for loop
Start
false
for
Exit loop
condition
true
statements End
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 51
The for loop Contd…
Syntax:
for (exp1;exp2;exp3)
{
statement1;
statement2;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 52
Using for
• #include <iostream>
• using namespace std;
• int main( )
• {
• int i;
• for(i=0;i<=10;i++)
• cout<<"\nValue of i is : "<<i;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 53
Nesting of for loop
1. #include <iostream>
2. using namespace std;
3. int main( )
4. {
5. int i,j;
6. for (j=1;j<=12;j++)
7. {
8. for (i=1; i<=10;i++)
9. {
10. cout<<i*j<<"\t";
11. }
12. }
13. return 0;
14. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 54
Control Flow Transfer Statements
break;
continue;
goto labelName;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 55
Using ‘break’
• #include <iostream>
• using namespace std;
• int main( )
• {
• int i;
• for(i=1;i<=20;i++)
• {
• if(i%14==0)
• break;
• cout<<i<<"\n";
• }
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 56
Using ‘continue’
• #include <iostream>
• using namespace std;
• int main( )
• {
• int i;
• for(i=1;i<=20;i++)
• {
• if(i%2!=0)
• continue;
• cout<<"\nValue of i is : "<<i;
• }
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 57
Using ‘goto’
• #include <iostream>
• using namespace std;
• int main( )
• {
• cout<<"\nhello 1";
• cout<<"\nhello 2";
• goto a;
• cout<<"\nhello 3";
• cout<<"\nhello 4";
• a:
• cout<<"\nhello 5";
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 58
Type Conversion
Implicit Conversion:
In C+ +, the following program code is valid, and will result in
proper evaluation:
int i, j;
char k;
...
i = j + k;
The type of the variable k is converted from char to int, and
then used in the expression.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 59
Implicit Conversion
1. #include <iostream>
2. using namespace std;
3. int main( )
4. {
5. float result = 4 / 3;
6. cout<<result<<"\n";
7. return 0;
8. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 60
Explicit Conversion
Consider the following program code:
long i;
int j, k;
i = j + k;
Explicit casting :
i = (long) j + k;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 61
Explicit Conversion contd…
1. #include <iostream>
2. using namespace std;
3. int main( )
4. {
5. float result= (float) 4/3;
6. cout<<"Result = "<<result<<"\n";
7. return 0;
8. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 62
Module 2: Arrays
• Overview
Definition
Array of integers and characters
Initialization of arrays
String manipulation functions
Multidimensional Arrays
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 63
Arrays
• Collection of variables of
Similar data type
Referred by a common name
Stored in consecutive memory locations
Array values can be accessed via its subscript
e.g.
int marks[5];
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 64
Array example
• #include<iostream>
• using namespace std;
• # define MAX_VALS 4
• int main ( ){
• int values[4] ,i, j, sum=0;
• cout<<"Enter 4 values....";
• for(i = 0; i<MAX_VALS;i++) {
• cin>>j;
• values [i] = j ;
• sum += j;
• }
• cout<<"\n values were : ";
• for (i = 0 ; i < MAX_VALS; i++)
• cout<<"\n"<<values[i];
• cout<<"\n Total : "<<sum<<endl<<"Average:
"<<(float)sum/MAX_VALS<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 65
Arrays of Characters
1. #include<iostream>
2. using namespace std;
3. # define MAX 5
4. int main( )
5. {
6. char str[MAX];
7. int i;
8. cout<<"Enter 5 characters"<<endl;
9. for (i = 0; i < MAX; i++)
10. cin>>str[i];
11. cout<<"\nThe characters were: ";
12. for (i = 0; i < MAX; i++)
13. cout<<str[i];
14. return 0;
15. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 66
The ‘cin’ and strings
1. #include<iostream>
2. using namespace std;
3. #define MAX 10
4. int main( )
5. {
6. char str[MAX];
7. cout<<"Enter a string: ";
8. cin>>str;
9. cout<<str<<"\n";
10. return 0;
11. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 67
Initialisation of Arrays
int score[11] =
{89,125,56,45};
0 1 2 3 4 5 6 7 8 9 10
score 89 125 56 45 0 0 0 0 0 0 0
100 102 104 106 108 110 112 114 116 118 120
Memory locations
ArrayName
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 68
Char Arrays or Strings
char name[10]=“Rosy”;
0 1 2 3 4 5 6 7 8 9
R o s y \0
100 101 102 103 104 105 106 107 108 109
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 69
Some string manipulation functions
strlen ( )
strcpy ( )
strcat ( )
strcmp ( )
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 70
Some string manipulation functions
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 71
Using string functions
• #include<string.h>
• int main( ){
• char str1[20]="C ",str2[20]="Programming in ",str3[30]="";
• cout<<"Length of str1 is "<<strlen(str1);
• strcat(str2,str1); //append str1 at the end of
str2
• cout<<"\nstr2 is "<<str2;
• strcat(str3,str2);
• strcat(str3,"language");
• cout<<"\nlength of "<<str3<<" is "<<strlen(str3);
• if( strcmp("apple","Apple")>0)
• cout<<"\nfirst string is greater";
• else if ( strcmp("apple","Apple")<0)
• cout<<"\nsecond string is greater";
• else
• cout<<"\nboth strings are equal“;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 72
Multi-Dimensional Arrays
Syntax:
datatype variableName
[index1]….[indexn]
The 3rd element from the 1st row can be accessed by,
student[2][1]
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 73
A double dimensional array
1. int main( ){
2. int total=0,i,j,col=1,row=2;
3. int score[3][11]= {
4. {95,25,56,45,75},
5. {14,22,88,37,95,12},
6. {84,25,16,23,6,89,12,34}
7. };
8. for(i=0;i<3;i++) {
9. cout<<"Test: "<<i+1<<"\n"<<"scores:";
10. for(j=0;j<10;j++) {
11. cout<<score[i][j]<<' ';
12. total=total+score[i][j];
13. }
14. cout<<"\nTotal : "<<total<<endl<<endl; total=0;
15. }
16. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 74
Strings
char days[7][10]={ “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”,
“Sunday” };
100
0 M o n d a y \0
Index 110 Memory
1 T u e s d a y \0
120 Locations
2 W e d n e s d a y \0
130
3 T h u r s d a y \0
140
4 F r i d a y \0
5 150
S a t u r d a y \0
6 160
S u n d a y \0
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 75
Printing the array of strings
1. int main( ){
2. char month[10]="May";
3. char days[7][10]={
4. "Monday",
5. "Tuesday",
6. "Wednesday",
7. "Thursday",
8. "Friday",
9. "Saturday",
10. "Sunday"
11. };
12. cout<<"\nMonth is : "<<month;
13. for(int i=0;i<7;i++)
14. cout<<" \n Day is :"<<days[i]<endl;
15. return 0;
16. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 76
Module 3: Functions
• Overview
Definition
User defined functions
Storage Classes
Recursion
Default Arguments
Function Overloading
Inline functions
Scope Resolution operator
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 77
Functions
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 78
Library functions
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 79
The User defined functions
• Syntax:
return_type function_name (argument list)
argument declarations
{
declarations;
executable statements;
}
Eg:
int show_age(int age );
int cal_age(char );
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 80
Creating a user defined function
Function header or function prototype
{
if(value % 2 == 0) Function body
return 1;
else
return 0;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 81
Function types
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 82
Program to compute power of an integer
1. int power (int,int);
2. int main ( ){
3. int i;
4. for (i = 0; i < 10; i++)
5. cout<<i<<"\t"<<power(2, i)<<"\t"<<power (3,
i)<<endl;
6. return 0;
7. }
8. int power(int base,int n){
9. int i, p;
10. p = 1;
11. for (i = 1; i <= n; i++)
12. p *= base;
13. return p;
14. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 83
Classification of variables
Based on position
Local
Global
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 84
Scope of variables
Local variables Global variables
Declared within any function body Declared outside of any function body
Available only within declaring Available to the entire program, hence can
function be shared by other functions
Are lost as soon as the declaring Are lost as soon as the declaring
function body terminates application or program terminates
• void fun( ) • int k=10; /* global to prg */
• { • void fun( )
• int i=10; /*local to fun */ • {
• } • int i=10; k=35;
• void foo( ) • }
• { • void foo( )
• int i=10; /*local to foo */ • {
• } • int i=10; cout<<k;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 85
Storage Classes
Types :
Automatic
Register
Static
Extern
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 86
Automatic
Keyword : auto
Locations : Memory
Initial Value: Garbage
Scope : Only in the function or block in which it is
declared
Lifetime : Only in the function or block in which it is
declared
Example :
auto int num1;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 87
Register
Keyword : register
Locations : Register
Initial Value: Garbage
Scope : Only in the function or block in which it is
declared
Lifetime : Only in the function or block in which it is
declared
Example :
register int num1;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 88
Static
Keyword : static
Locations : Memory
Initial Value: 0
Scope : Only in the function or block in which it is
declared
Lifetime : From the point of declaration to the end of the
program
Example :
static int num1;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 89
Difference between auto and static
variables
1. #include<iostream>
2. using namespace std;
4. void inc( );
5. void inc_i( );
7. int main( )
8. {
9. cout<<"Invoking function inc( )....";
10. inc( );
11. inc( );
12. inc( );
13. cout<<"Invoking function inc_i( )....";
14. inc_i( );
15. inc_i( );
16. inc_i( );
17. return 0;
18. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 90
Difference between auto and static
variable
• void inc( ){
• int i=0; /* auto variable */
• i++;
• cout<<"\nValue of i:"<<i;
• }
• void inc_i( ){
• static int i; /* static variable */
• i++;
• cout<<"\nValue of i:"<<i;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 91
Extern
Keyword : extern
Locations : Memory
Initial Value: last value attained in a previous file
Scope : global
Lifetime : global
Example :
extern int num1;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 92
Example of extern
1. /* Source file 1. /* Source file
F04GlobalVar.cpp */ F04ExternExample.cpp
*/
2. int n = 3;
3. void alter ( ); • extern int n;
4. int main ( ) • void alter ( )
5. { • {
6. cout<< n; • n = 10;
• }
7. alter( );
8. cout<< n;
9. return 0;
10. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 93
Making Data and Functions Private
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 94
Recursion
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 95
Finding factorial using recursion
1. #include<iostream>
2. using namespace std;
3. int factorial(int x) {
4. if(x==1)
5. return 1;
6. else
7. x=x*factorial(x-1);
8. return x;
9. }
10. int main( ) {
11. int num;
12. num = factorial(5);
13. cout<<"\nFactorial of 5 is "<<num;
14. return 0;
15. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 96
Default Arguments
Eg:
cin.ignore(1); & cin.ignore(4,’\n’);
square(6); & square(6, 10);
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 97
Using default arguments
• int add(int,int=0);
• int main( ){
• cout<<add(10,20)<<endl;
• cout<<add(8)<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 98
Function overloading
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 99
Using function overloading
1. void add(int x,int y){ cout<<x+y<<endl;
2. }
3. void add(float x,float y) { cout<<x+y<<endl;
4. }
5. void add(int x,float y){ cout<<x+y<<endl;
6. }
7. void add(float x,int y){ cout<<x+y<<endl;
8. }
9. int main( ){
10. add(10,10);
11. add(30,20.15f);
12. add(16.57f,4);
13. add(3.25f,6.44f);
14. return 0;
15. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 100
Ambiguity
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 101
Inline functions
• Syntax
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 102
Scope Resolution operator (::)
1. int count = 0;
• int main(void)
• {
• int count = 0;
• ::count = 1; // set global count to 1
• count = 2; // set local count to 2
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 103
Module 4: Pointers and References
• Overview
Definition and declaration
Pointer to an array
Pointer arithmetic
Pointers as function arguments
Array of pointers
Pointer to pointer
Command line arguments
Function pointers
References in C++
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 104
Pointer
Name Num
Value 189
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 105
Pointer declaration
datatype *pointerVariableName;
pointer declaration
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 106
Pointer declaration & initialization
Syntax for Initialization :
Address Of
Declaration-cum-Initialization
datatype *pointerVariableName = &variable;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 107
Pointer example
1. int main( ) {
2. int x=10,y=20,z=30;
3. int *ptr = &x;
65514
5. cout<<"Value of
x:"<<x<<endl;
65516
6. cout <<"Value at
*ptr:"<<*ptr<<endl;
65518
7. cout <<"Value at 65524 ptr
&x:"<<*&x<<endl<<endl;
65520
30 z
9. cout <<"Address of
x:"<<(unsigned)( &x)<<endl; 65522
10. cout <<"Address pointed by the 20 y
pointer:"<<(unsigned)ptr<<endl 65524
; 10 x
6. cout <<"Address of
65518
x:"<<(unsigned)(&y)<<endl; 65524 ptr
7. cout <<"Address pointed by the
pointer:"<<(unsigned)ptr<<endl; 65520 30 z
8.
9. cout<<"The size of the pointer 65522
20 y
is:"<<sizeof(ptr)<<endl;
10. return 0; 65524 10 x
11. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 109
Pointer to an Array
1. int main ( ){
2. int ary[5]={10,20,30,40,50};
3. int *ptr, i;
4. for(i=0;i<5;i++){
5. ptr=&ary[i];
6. cout<<*ptr<<'\t';
7. }
8. cout<< endl<<"Size of pointer:"<<sizeof(ptr);
9. cout<<endl<< "Size of array:"<<sizeof(ary)<<endl;
10. return 0;
11. } 0 1 2 3 4
ary 10 20 30 40 50
100 102 104 106 108 110
ptr
100
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 110
Pointer arithmetic
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 111
Pointer addition
• ptr++ or ptr-- :
Increments or decrements the pointer by the size in bytes
depending upon the data for which pointer is declared
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 112
Accessing array elements using pointers
Hence, the previous program can also be written as:
3. int main( ){
4. int ary[5]={10,20,30,40,50};
5. int *ptr= ary;
6. for(;ptr<&ary[5];ptr++)
7. cout<<*ptr;
8. return 0;
9. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 113
Pointers to Character Strings
1. void copy_string (char *from, char *to)
2. {
3. for ( ; *from != '\0'; ++ from, ++ to)
4. *to = *from;
5. *to = '\0';
6. }
Or, better still:
8. void copy_string (char *from, char *to)
9. {
10. while (*from)
11. *to ++ = *from ++;
12. *to='\0';
13. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 114
Pointer subtraction
1. int main( ){
2. int ary[5]={10,20,30,40,50};
3. int *ptr,*ptr1=ary;
4. for(ptr=ary;ptr<&ary[5];ptr++){
5. cout<<*ptr;
6. }
7. cout<<“Number of elements in the array are:”<<ptr-
ptr1;
8. return 0;
9. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 115
Example of pointer subtraction
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 116
Pointers as function arguments
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 117
Pass by value
• int main( ) {
• void swap(int, int);
• int x=10, y=20;
• cout<<x<<‘\t’<<y; // 10 20
• swap(x,y);
• cout<<x<<‘\t’<<y; // 10 20
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 118
Pass by address
• int main( ) {
• void swap(int*, int*);
• int x=10, y=20;
• cout<<x<<‘\t’<<y; // 10 20
• swap(&x,&y);
• cout<<x<<‘\t’<<y; // 20 10
• return 0;
• }
• void swap(int *x, int *y) {
• int temp;
• temp=*x;
• *x=*y;
• *y=temp;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 119
Pass by value vs. Pass by address
main( ) main( )
x y x y
10 20 10 20
65510 65512 65510 65512
swap(x,y); swap(&x,&y);
x y x y
10 20 65510 65512
65524 65526 65524 65526
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 120
Arrays of Pointers
Examples:
char *argv[4];
Syntax:
datatype *pointerName[arraySize];
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 121
Array of pointers
• int main ( )
• {
• int num1 = 1, num2 = 2, num3 = 3;
• int i;
• int *iptr [3];
• iptr [0] = &num1;
• iptr [1] = &num2;
• iptr [2] = &num3;
• for (i = 0; i < 3; i ++)
• cout<< *iptr [i];
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 122
Array of pointers
int main( ) {
int ary1[3]={10,20,30};
int ary2[5]={2,4,6,8,10};
int ary3[7]={8,16,32,64,128,256,512},i;
int *ptr[3]; //collection of 3 pointers in an
array
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 124
Pointer to pointer
int main( )
{
65514
int x=10;
65516
int *ptr1=&x;
65518
int **ptr2 = &ptr1;
65520 ptr3
int ***ptr3 = &ptr2; 65520
65522 ptr2
cout<<***ptr3; 65522
return 0; 65524 ptr1
} 65524
10 x
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 125
Command Line Arguments
Syntax
main( int argc, char *
argv [ ])
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 126
Accessing command line parameters
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 127
Function pointers
void show1(char x, char y) {
cout<<"\n Characters : “<<x<<“ & ”<<y;
}
void show2(int x, int y) {
cout<<"\n Numbers : “<<x<<“ & ”<<y;
}
int main( ){
void (*ptr)(int,int);
ptr=&show1; ptr('A','B');
ptr=&show2; ptr(50,60);
return 0;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 128
References
Eg:
int i;
int &x=i;
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 129
Swapping two integers with references
• void swap(int &int1,int &int2){
• int temp = int2;
• int2 = int1;
• int1 = temp;
• }
• int main( ) {
• int num1 = 10;
• int num2 = 20;
• cout<<"Before swap:\tnum1: "<<num1<<"\tnum2:
"<<num2<<endl;
• swap (num1, num2);
• cout <<"After swap :\tnum1: "<<num1<<"\tnum2:
"<<num2<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 130
Using References
1. int look_up (const int *array, int size, int value, int &occurs){
2. int index = -1;
3. for (int ix = 0; ix < size; ++ix)
4. if(array [ix] == value){
5. if (index == -1) index = ix;
6. ++occurs;
7. }
8. return index;
9. }
10. int main( ){
11. int arry[]={10,24,10,35,62,10,24},no_elements=0;
12. int position=look_up(arry,(sizeof arry)/(sizeof(int)),35,no_elements);
13. if(position==-1)
14. cout<<"Number is not in the array"<<endl;
15. else{
16. cout<<"Position:"<<position<<endl;
17. cout<<"No of occurances:"<<no_elements<<endl;
18. }
19. return 0;
20. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 131
Module 5:Classes and Objects
• Overview
Classes and Objects
this pointer
Constructors
Dynamic Memory Allocation
Destructors
static Data Members and Member Functions
const Functions
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 132
Classes
• Classes are user defined data types
• Syntax
class tag_name
{
private:
// --- member variables & functions
protected:
// --- member variables & functions
public:
// --- member variables & functions
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 133
Using class declaration
• class BankAccount { //default
access is private.
• unsigned acc_num;
• double balance;
• void deposit(double amt){
• balance+=amt;
• }
• void withdraw(double amt){
• balance-=amt;
• }
• void display( ){
• cout<<"Account NUMBER-"<<acc_num<<":"<<"\nRs
"<<balance<<"\n";
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 134
Access Specifiers
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 135
Using Access Specifiers
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 137
Scope Resolution operator & class
members
1. #include <iostream>
2. using namespace std;
3. class X
4. {
5. public:
6. int count;
7. };
8. int X::count = 10; // define data member
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 138
Defining member functions using
operator ::
1. class BankAccount {
2. unsigned acc_num;
3. double balance;
4. public:
void setdata ( unsigned , double)
• void deposit(double);
• void withdraw(double);
• void display( );
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 140
Constructors
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 141
Constructors
• Syntax to declare a constructor
class_name (argument_list);
class_name::class_name(argument_list){
// body of constructor function;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 142
Types of Constructors
• Default constructor
• Parameterized constructor
• Constructors with default arguments
• Copy constructors
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 143
Default Constructors
• Syntax
class name{
public:
name( ){
// executable statements;
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 144
Default Constructors Contd …
• BankAccount ( )
{ // default
constructor
• min_bal = 5000;
• acc_num = 2004;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 145
Parameterized constructor
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 146
Constructor Overloading
• class BankAccount { //default access is
private.
• unsigned acc_num;
• double balance;
• public:
• BankAccount( ):balance(5000),acc_num(2004)
• {}
• BankAccount(unsigned x):balance(5000),acc_num(x)
• {}
• BankAccount(double bal,unsigned
x):balance(bal),acc_num(x)
• {}
• void deposit(double amt){
• balance+=amt;
• }
• void withdraw(double amt){
• balance-=amt;
• }
• void display( ){
• cout<<"Account
NUMBER-"<<acc_num<<":"<<"\nRs "<<balance<<"\n";
• Software Pvt.}Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Pragati 147
Constructor Overloading Contd …
• int main( ){
• BankAccount B1;
• B1.deposit(3500);
• B1.display( );
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 148
Constructors with default arguments
• //BankAccount (unsigned
x):balance(5000),acc_num(x)
• //{ }
•
• //BankAccount (double bal, unsigned x): balance
( bal ), acc_num (x)
• //{ }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 149
Explicit keyword
• #include<iostream>
• using namespace std;
• class BankAccount{
• unsigned acc_num;
• double balance;
• public:
• explicit BankAccount ( unsigned x ): balance ( 5000 ), acc_num
(x)
• {}
• bool compare_bal ( BankAccount s ){ return s.balance >
balance; }
• void deposit(double amt){
• balance+=amt;
• }
• void withdraw(double amt){
• balance-=amt;
• }
• void display(){
• cout<<"Account
NUMBER-"<<acc_num<<":"<<"\nBalance =Rs "<<balance<<"\n";
Pragati•Software Pvt. Ltd.,
} 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 150
Explicit keyword Contd …
1. int main( ){
2. BankAccount B2=3005; //error
3. B2.deposit(8000);
4. cout<<"\nB2 details...."<<endl;
5. B2.display( );
7. return 0;
8. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 151
Copy constructor
OR
class_name new_object(source_object);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 152
Copy constructor example
• class BankAccount{
• unsigned acc_num;
• unsigned balance;
• public:
• BankAccount():balance(5000),acc_num(2004)
• {}
• BankAccount(BankAccount
&obj):balance(obj.balance),acc_num(2005)
• {}
• void deposit(unsigned x){
• balance+=x;
• }
• void withdraw(unsigned x){
• balance-=x;
• }
• void display( ){
• cout<<"Account
NUMBER-"<<acc_num<<":"<<"\nRs "<<balance<<"\n";
• cout<<"\n";
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 153
Copy constructor example Contd …
• int main( ){
• BankAccount B1;
• cout<<"\nB1 deposits 3500\n";
• B1.deposit(3500);
• B1.display( );
• cout<<"\n";
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 154
Dynamic Allocation
Eg:
int *pi=new int;
int *pia = new int[10];
LinkList *ptr = new LinkList( );
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 155
Dynamic Allocation Contd …
1. class BankAccount
2. {
3. unsigned acc_num;
4. double balance;
5. public:
6. BankAccount(unsigned x,double bal) : acc_num ( x ),
balance ( bal )
7. {}
8. void display( )
9. {
10. cout<<acc_num<<":"<<balance<<"\n";
11. }
12. };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 156
Dynamic Allocation Contd …
• int main( )
• {
• BankAccount *ptr=new BankAccount(333,3500);
• ptr->display( );
• delete ptr;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 157
Destructors
• Syntax
class name{
public:
name( ){
// executable statements;
}
~name( ){
// executable statements;
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 158
Destructors Example
• class BankAccount
• {
• unsigned acc_num;
• double balance;
• public:
• BankAccount( unsigned x, double bal) : acc_num ( x )
, balance( bal )
• { }
• ~BankAccount( )
• {
• cout<<"This is the bank account
destructor!"<<endl;
• }
• void display( ){
• cout<<acc_num<<":"<<balance<<"\n";
• }
• Software
Pragati }; Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 159
Destructors Example Contd…
1. int main( )
2. {
3. cout<<"For object created on the heap..."<<endl;
4. BankAccount *ptr=new BankAccount(333,3500);
5. delete ptr;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 160
Static Data Members
Syntax to declare:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 161
Static Member functions
Syntax to declare:
Syntax to access:
object::function_name(argument_list);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 162
Static Data Members and Member Functions
Example
• class BankAccount {
• unsigned acc_num;
• double balance;
• static int num;
• public:
• BankAccount ( ){
• acc_num=450;
• balance=5000.0;
• ++num;
• }
• BankAccount ( unsigned x, double bal){
• acc_num=x;
• balance=bal;
• ++num;
• }
• void deposit ( double amt){
• balance+=amt;
• }
• static void showNoObjects( ){
• cout<<"\nThe total number of objects created
are:"<<num<<endl;
• Software Pvt.}Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Pragati 163
Static Data Members and Member Functions
Example
• void display( ){
• cout<<"\nAccount
NUMBER-"<<acc_num<<":"<<"\nRs "<<balance<<"\n";
• }
• };
• int BankAccount :: num;
• int main( ){
• BankAccount S1;
• S1.deposit( 3500 );
• S1.display( );
• int main( )
• {
• noon.display( );
• noon.setTime(5,6,7); //will be an error ;
• cout<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 166
Mutable keyword
• class Time{
• int hr, min, sec;
• mutable int hr1;
• public:
• Time (int h , int m ,int s){
• hr=h;
• min=m;
• sec=s;
• }
• void setTime (int h, int m, int s) {
• hr=h;
• min=m;
• sec=s;
• }
• void display( ) const {
• hr1 = 2;
• cout<<endl<<"The time is:";
• cout<<hr<<":"<<min<<":"<<sec;
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 167
Module 6: Friend keyword
• Overview
Friend Functions
Friend Classes
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 168
Friend functions
• Used to access the private members of a class by non-
member functions
function_name(argument list);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 169
Friend functions example
• class Time{
• int hr,min,sec;
• friend Time calculateTime(Time,Time);
• public:
• Time( ) {
• hr=0;
• min=0;
• sec=0;
• }
• Time(int hr1,int min1,int sec1) {
• hr=hr1;
• min=min1;
• sec=sec1;
• }
• void display( ){
• cout<<hr<<":"<<min<<":"<<sec<<endl;
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 170
Friend functions example contd…
• //function calculateTime requires to access the private
members of class Time
• Time calculateTime (Time t1,Time t2)
• {
• Time result;
• result.hr=t1.hr+t2.hr;
• result.min=t1.min+t2.min;
• result.sec=t1.sec+t2.sec;
• return result;
• }
• int main( )
• {
• Time t1(3,3,5), t2(2,5,6) ;
• Time t3;
• t3=calculateTime(t1,t2);
• t3.display( );
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 171
Friend classes
• class Node{
• int x;
• friend class LinkedList;
• public:
• Node( ) : x(100)
• {}
• };
• class LinkedList {
• Node obj;
• public:
• void display( ){
• cout<<"the value of x is:"<<obj.x<<endl;
• }
• };
• int main( )
• {
• LinkedList ll;
• ll.display( );
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 172
Module 7: Operator Overloading
• Overview
Overloading The Binary + operator
Overloading The prefix operator
Overloading The postfix operator
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 173
Operator overloading
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 174
Operator Overloading
+ - * / %
^ = < > !=
+= -= & new delete
<> <= >= << >>
&& || ++ -- ()
sizeof, . , :: , ?:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 175
Operator Overloading
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 176
Overloading the Plus operator as a Member
function
1. class Time{
2. int hr, min, sec; • Time
3. public: operator+(Time t2)
4. Time( ) • {
5. { • Time result;
6. hr=0; • result.hr=hr+t2.hr;
7. min=0; •
8. sec=0; result.min=min+t2.mi
9. } n;
10. Time (int hr, int min, int •
sec) { result.sec=sec+t2.sec
11. this->hr=hr; ;
12. this->min=min; • return result;
13. this->sec=sec; • }
14. } • };
15. void display( ) {
16.
cout<<hr<<":"<<min<<":"<
<sec<<endl;
17.Software}
Pragati Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 177
Overloading the Plus operator as a Friend
function
• class Time{
• int hr, min, sec; • Time operator+(Time
• public:
t1,Time t2)
• Time( ){ • {
• hr=0; • Time result;
• min=0; • result.hr=t1.hr+t2.hr;
• sec=0; •
• } result.min=t1.min+t2.mi
• Time( int hr, int min, int
sec){ n;
• •
this->hr= hr;
• result.sec=t1.sec+t2.sec;
this->min= min;
• return result;
• this->sec= sec;
• }
• }
• void display( ){
•
cout<<hr<<":"<<min<<":"<
<sec<<endl;
• }
• Software
Pragati friendPvt. Ltd.,Time
312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 178
Operator Overloading Example
• int main( )
• {
• Time t1(3,3,5),t2(2,5,6);
• Time t3;
• t3=t1+t2; //this invokes the
operator overloaded function
• t3.display();
• cout<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 179
Overloading the Prefix operator as a Member
function
1. class Time{
2. int hr, min, sec; • Time
3. public: operator++( )
4. Time( ) • {
5. { • Time result;
6. hr=0; • result.hr=++hr;
7. min=0; •
8. sec=0; result.min=++min;
9. } •
10. Time (int hr, int min, int sec) { result.sec=++sec;
11. this->hr=hr; • return result;
• }
12. this->min=min;
• };
13. this->sec=sec;
14. }
15. void display( ){
16.
cout<<hr<<":"<<min<<":"<<se
c<<endl;
17. }
18.Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Pragati 180
Overloading the Prefix operator as a Friend
function
• class Time{
• int hr, min, sec;
• public: • Time operator++
• Time( ){ (Time t)
• hr=0; • {
• min=0; • Time result;
• sec=0; • result.hr=++t.
• } hr;
• Time( int hr, int min, int sec){ •
• this->hr= hr; result.min=++t.
• this->min= min;
•
min;
this->sec= sec;
• }
• result.sec=++t.
• void display( ){ sec;
• • return result;
cout<<hr<<":"<<min<<":"<<sec< • }
<endl;
• }
• friend Time operator++(Time);
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 181
Operator Overloading for prefix operator
Example
The call for both methods:
• int main( )
• {
• Time t2(2,5,6);
• Time t3;
• t3=++t2; //this invokes the
operator overloaded function
• t3.display( );
• cout<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 182
Postfix operator overloaded
As a member function: As a friend function:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 183
Module 8: Inheritance
• Overview
Inheritance Access Specifier
Single Inheritance
Multiple Inheritance
Hybrid Inheritance
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 184
Inheritance
• Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 186
Types of inheritance
• Single
• Multilevel
• Multiple
• Hybrid
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 187
Single Inheritance: The Base Class
• class BankAccount{
• protected:
• int accNo;
• double balance;
• public:
• BankAccount( )
• {
• accNo=0;
• balance=5000;
• }
• void display( )
• {
• cout<<"Account Number:"<<accNo <<" has
balance = "<<balance;
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 188
Single Inheritance :The Derived class
1. class SavingAccount : public BankAccount {
2. float minimumBalance;
3. float rateOfInterest;
4. public:
5. SavingAccount(float rofI)
6. {
7. rateOfInterest=rofI;
8. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 189
Single Inheritance Contd…
1. int main( )
2. {
3. SavingAccount S1(8.75f);
4. S1.display( );
6. return 0;
7. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 190
Constructor Ordering
1. SavingAccount S1(8.75f);
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 191
Constructor Ordering contd…
• class BankAccount{
• protected:
• int accNo;
• double balance;
• public:
• BankAccount(int AccNO,double bal) {
• accNo=AccNO;
• balance=bal;
• }
• };
• class SavingAccount : public BankAccount {
• float minimumBalance;
• float rateOfInterest;
• public:
• SavingAccount(int AccNO,double bal,float
rofI):BankAccount(AccNO,bal)
• { rateOfInterest=rofI;
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 192
Constructor Ordering contd…
int main( )
{
SavingAccount S1(204,10000.0,8.75f);
S1.display( );
return 0;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 193
Multiple Inheritance
class Membership{ class SavingAccount
protected: {
char typeOfMembership; static float minimumBalance;
public: float rateOfInterest;
Membership( ) public:
{} SavingAccount( )
Membership(char type) {}
{ SavingAccount(float rofI) {
rateOfInterest=rofI;
typeOfMembership=type;
} }
void display() void display( ) {
{ cout<<"\nThe rate of
cout<<"\nThe Interest applied
Membership is of is:"<<rateOfInterest;
}
type:"<<typeOfMembershi };
p; float
} SavingAccount::minimumBalance=5
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 194
Multiple Inheritance Contd…
• int main( )
• {
• LoanAccount B1;
• B1.display( ); //Ambiguity
error!
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 195
Hybrid Inheritance
class BankAccount{
protected:
int accNo;
double balance;
public:
BankAccount( ) {
accNo=0;
balance=0;
}
BankAccount(int AccNo,double bal) {
accNo=AccNo;
balance=bal;
}
void display( ) {
cout<<"Account Number:"<<accNo<<" has balance
= "<<balance<<endl;
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 196
Hybrid Inheritance Contd…
int main( )
{
LoanAccount B1;
B1.display( );
return 0;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 198
Module 9: Polymorphism and Abstract
classes
• Overview
Virtual functions
Polymorphism Example
Abstract classes
Virtual Destructors
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 199
Virtual functions
• Syntax
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 200
Virtual functions
class BankAccount{
protected:
int accNo;
double balance;
public:
BankAccount( ){ }
BankAccount(int AccNo,double bal)
{
accNo=AccNo;
balance=bal;
}
/*For polymorphism this function has to declared as virtual*/
virtual void display( )
{
cout<<"Account Number:"<<accNo<<" has balance =
"<<balance<<endl;
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 201
Polymorphism Example
class SavingAccount : public
BankAccount class CurrentAccount : public
{ BankAccount
float minimumBalance; {
float rateOfInterest; protected:
public: double overDraftLimit;
SavingAccount(int AccNo, public:
double bal, CurrentAccount(double
float odl)
rofI):BankAccount(AccNo,bal {
) overDraftLimit=odl;
{ }
rateOfInterest=rofI; void display( )
{
} cout<<"\nThe
void display( ) { overdraft Limit for this
BankAccount::display(); accounts is:“
cout<<"\nThe rate of <<overDraftLimit<<endl;
Interest applied
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 202
Polymorphism Example
int main( )
{
BankAccount B1(203,10000.0);
BankAccount *Baseptr=&B1;
Baseptr->display( );
SavingAccount S1(204,3000.0,9.0f);
Baseptr=&S1;
Baseptr->display( );//calls SavingAccount.display() if
display() is made virtual in base class, else calls
BankAccount.display( );
CurrentAccount C1(5000.0);
Baseptr=&C1;
Baseptr->display( );
//calls CurrentAccount.display( ) if display( ) is made
virtual in base class, else calls BankAccount.display( );
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 203
Abstract classes
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 204
Abstract classes Example
class BankAccount{
protected:
int accNo;
double balance;
public:
BankAccount( ){ }
BankAccount(int AccNo,double bal)
{
accNo=AccNo;
balance=bal;
}
/*For making this function a pure virtual function it has to
equated to zero*/
virtual void display( )=0;
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 205
Virtual Destructors
class BankAccount {
protected:
int accNo;
double balance;
public:
BankAccount( ){ }
BankAccount(int AccNo,double bal) {
accNo=AccNo;
balance=bal;
}
/*For polymorphism this function has to declared as virtual*/
virtual void display( ){
cout<<"Account Number:"<<accNo<<" has balance =
"<<balance<<endl;
}
/* virtual destructors*/
virtual ~BankAccount( ) {
cout<<"\nInvoking base class destructor...";
}
};Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Pragati 206
Virtual Destructors
class SavingAccount: public BankAccount {
float minimumBalance;
float rateOfInterest;
public:
SavingAccount ( int AccNo, double bal, float rofI) : BankAccount(
AccNo, bal) {
rateOfInterest = rofI;
}
void display( ) {
BankAccount:: display( );
cout <<"\n The rate of Interest applied is:"<<
rateOfInterest;
}
~SavingAccount ( ){
cout<<"\nInvoking Saving account destructor...";
}
};
int main( ){
BankAccount * Baseptr=new SavingAccount ( 204,
3000.0, 9.0f);
delete Baseptr;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 207
Module 10: Streams
• Overview
Stream class hierarchy
cin.get ( )/ cin.getline( ) methods
cin.ignore( ) method
Manipulators
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 208
Stream Classes
Advantages:
No formatting characters in streams.
Overloading of existing operators and functions possible
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 209
Stream class hierarchy
ios
istream ostream
iostream
ifstream ofstream
fstream
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 210
Reading strings
• Syntax
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 211
The get function
1. #include<iostream>
2. using namespace std;
3. #define MAX 9
4. int main( )
5. {
6. char str0[MAX];
7. cout<<"Enter a string: ";
8. cin.get(str0,MAX);
9. cout<<str0<<"\n";
10. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 212
The getline function
1. #include<iostream.h>
2. #define MAX 20
3. int main( )
4. {
5. char str1[MAX];
6. cout<<"Enter a string: ";
7. cin.getline(str1,MAX,'.');
8. cout<<str1<<"\n";
9. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 213
Limitations of the get and getline
functions
1. int main( )
2. {
3. char str[30];
4. int code;
5. cout<<"Enter the code of the Employee ";
6. cin>>code;
7. cout<<"Enter the name of the Employee ";
8. cin.getline(str,30);
9. cout<<str<<" has code:"<<code;
10. cout<<"\n";
11.}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 214
cin.ignore( )
Syntax:
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 215
Using cin.ignore( )
1. int main( )
2. {
3. char str[30];
4. int code;
5. cout<<"Enter the code of the Employee ";
6. cin>>code;
7. cin.ignore(4,'\n');
8. cout<<"Enter the name of the Employee ";
9. cin.getline(str,30);
10. cout<<str<<" has code:"<<code;
11. cout<<"\n";
12. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 216
Manipulators
endl ‘\n’
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 217
Module 11: File I/O
• Overview
Opening/ Closing a file
reading /writing to a file char-by-char
reading /writing an object to a file
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 218
File i/o
ofstream
Used for file output operations
Derived class of ostream
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 219
Opening/Closing a file
• To close a file
using close function
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 220
Reading/Writing to File char-by-char
• #include<fstream>
• #include<iostream>
• using namespace std;
• int main( ) {
• char str[ ]= "Time flies over us, but leaves its
shadows behind\n";
• ofstream for_write (“ char_by_char.txt");
• cout<<"\nWriting into the file character by
character...";
• for ( unsigned i=0;i< strlen(str) ;i++)
• for_write.put(str[i]);
• for_write.close( );
• ifstream for_read("char_by_char.txt");
• char ch;
• cout<<"\nReading from the file character by
character and displaying ...\n";
• while(!for_read.eof( )){
• for_read.get(ch);
• cout<<ch;
Pragati•Software Pvt. Ltd.,
} 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 221
Reading/Writing an object to a File
#include<fstream>
#include<iostream>
using namespace std;
class Person{
char name[40];
int age;
public:
void getData( ){
cout<<"\nEnter name:";cin>>name;
cout<<"Enter age:";cin>>age;
}
void displayData( ){
cout<<name<<endl;
cout<<age<<endl;
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 222
Reading/Writing an object to a File
int main( )
{
Person P1,P2;
cout<<"\nEnter the data.\n";
P1.getData( );
ofstream data("Person_data.DAT");
cout<<"\nNow writing into the file..."<<endl;
data.write((char *)&P1,sizeof(Person));
data.close();
ifstream data1("Person_data.DAT");
cout<<"Now reading from the file..."<<endl;
data1.read((char *)&P2,sizeof(Person));
• Overview
Simple Exception Handling
Catch-All Handler
Re-throwing an exception
Catching class type exceptions
Handling derived class exceptions
Unwinding the stack
Throwing exceptions from constructors
Using set_terminate ( ) function
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 224
Exception handling
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 225
Syntax of a try…catch
try { ………….
throw exception;
………….
}
catch(type1 arg) {
//catch block
}
catch(type2 arg) {
//catch block
}
catch(type3 arg) {
//catch block
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 226
Simple Exception Handling
• #include<iostream>
• using namespace std;
• int main( )
• {
• try{
• cout<<"U R IN TRY BLOCK !!"<<endl;
• throw 10; //throw exception of type
integer.
• }
• catch(int){ //catch handler for integer.
• cout<<"U R IN CATCH BLOCK !!"<<endl;
• }
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 227
Catch-All Handler
int main( ) {
try{ int y;
cout<<"\n\nIn try block...";
cout<<"Enter the value of y:";
cin>>y;
if(y= =100)
throw y; //throw an excepiton of type int
else
cout<<"The value entered is:"<<y;
}
catch(float){
cout<<"In catch block for float... ";
}
catch(char *str){
cout<<"In catch block for string...“ <<str;
}
catch(...){
cout<<"In catch all block...";
}
cout<<"\nEND of program!!";
return 0;
} Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Pragati 228
Re-throwing an exception
void func1( ) int main( )
{ {
try{ try{
throw "SOMETHING went func1( );
wrong !!!"; }
} catch(const char
catch ( const char *s){ *s){
cout<<"Inside internal cout<<"\nBack in
handler !!"<<endl;
function main !!"<<endl;
cout<<"\n Rethrowing
the exception to the calling cout<<s<<endl;
function..."; }
throw; }
}
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 229
Catching class type exceptions
int main( ){
set_terminate ( Big_crunch);
try{
throw 1; //throw exception of type int.
}
catch ( char ){
cout<<"CAUGHT IN BLOCK";
}
return 0;
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 235
Module 13: RTTI and Casting Operators
• Overview
typeinfo class and using the typeid object
dynamic_cast
const_cast
static_cast
reinterpret_cast
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 236
RTTI
• Syntax: typeid(object);
• Uses #include<typeinfo.h>
class ClsBase{
virtual void func( ){
cout<<"In base class";
}
};
class class2{ };
int main( ){
int i,j;
float f;
char * chp;
ClsBase obj1,*ptr=0;
class2 obj2;
ClsDerv d1,*dptr=0;
if(typeid(obj1)==typeid(obj2))
cout<<"BOTH obj1 and obj2 are of the same
type"<<endl;
else
cout<<"obj1 and obj2 are not the same type"<<endl;
cout<<endl;
ptr=&obj1;
dptr=&d1;
cout<<"The type of *ptr is:"<<typeid(*ptr).name( )
<<endl;
cout<<"The type of *dptr is:"<<typeid(*dptr).name( )
<<endl;
ptr=&d1;
cout<<endl;
cout<<"Assigning address of derv class object to base
ptr......."<<endl;
• Syntax:
cast_name <type>
(expression);
• dynamic_cast
• static_cast
• const_cast
• reinterpret_cast
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 242
dynamic_cast
class Base void main( ){
{ Base *bp;
public: Derived *dp, d;
virtual void display( ) bp = &d;
{ if(!bp) cout<<"Casting failed";
cout<<"In base"; dp =
} dynamic_cast<Derived
}; *>(bp);
if(!dp)
class Derived:public Base cout<<"Casting failed";
{ else
public: cout<<"Dynamic casting
void display( ) successful !!”;
{ }
cout<<"In Derived";
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 243
const_cast
• int main( ){
• int num=5;
• cout<<"Number:"<<num;
• cout<<"Square:"<<square (&num);
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 244
static_cast
• int main( )
• {
• int cnt;
• double tmp;
• for(cnt=1; cnt<=10; cnt++)
• {
• tmp = static_cast<double> (cnt)/2;
• cout<<tmp<<"\n";
• }
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 245
reinterpret_cast
• int main( ){
• int num=100, add;
• int *ptr = #
• cout<<"num address:"<<(int)#
• add = reinterpret_cast<int> (ptr);
• cout<<"add value:"<<add;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 246
Module 14: Templates
• Overview
Template Function with one argument
Template Function with two arguments
Class Templates
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 247
Templates
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 248
Template Function with one argument
• template<class T>
• T abs(T a)
• {
• return (a<0)?-a:a;
• }
• int main( )
• {
• int num1=-34;
• num1=abs(num1);
• cout<<"Absolute value of the integer passed as an
argument: "<<num1<<endl;
• double num2=-23.45;
• num2=abs(num2);
• cout<<"Absolute value of the double passed as an
argument: "<<num2<<endl;
• float num3=3.56f;
• num3=abs(num3);
• cout<<"Absolute value of the float passed as an
argument: "<<num3<<endl;
• Software Pvt.cout<<endl;
Pragati Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 249
Template Function with two arguments
• template<class TY, class TB>
• void display(TY a,TB b){
• cout<<a<<endl<<b<<endl;
• }
• int main( )
• {
• int x=44;
• char y='S';
• char arr[]="Pragati software";
• float fp=7.8f;
• cout<<endl;
• display(x,y);
• cout<<endl;
• display(arr,fp);
• cout<<endl;
• return 0;
• }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 250
Class Template
• #include<iostream> 1. void pop( ){
• #include<string> 2. if(top>=0) {
• using namespace std; 3.
cout<<"Popping..."<<endl;
• template <class Any> 4. top--;
• class Stack{ 5. }
• Any arr[4]; 6. else
• int top; 7. cout<<"Stack is
• public: Empty!!";
• Stack( ) { 8. }
• top= -1; 9. void display( ){
• } 10. if(top<0) {
• void push( Any x) 11. cout<<"Stack is
• { Empty\n";
• if(top<4) 12. return;
• arr[ ++ top]=x; 13. }
• else 14. cout<<"Stack elements
• cout<<"Stack are:"<<endl;
Overflow!!"; 15. for(int i=top;i>=0;i--)
• Software}
Pragati Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
16. 251
Class Template
• int main( ) • cout<<"Stack of strings....."<<endl;
• { • Stack<string> S2;
• cout<<"Stack of • S2.push("Hi");
Integers....."<<endl; • S2.push("Hello");
• Stack<int> S1; • S2.push("What's");
• S1.push(3); • S2.display( );
• S1.push(33); • S2.pop( );
• S1.push(111); • S2.display( );
• S1.display( ); • cout<<"Pushing element ........."<<
• S1.pop( ); • S2.push("UP!!");
• S1.display( ); • S2.display( );
• cout<<"Pushing • cout<<"Popping 3 elements : "<<e
element"<<endl ; • S2.pop( );
• S1.push(23); • S2.pop( );
• S1.display( ); • S2.pop( );
• cout<<"Popping 3 • S2.display( );
elements"<<endl; •
• S1.pop( ); • return 0;
• S1.pop( ); • }
• SoftwareS1.pop(
Pragati );Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Pvt. Ltd., 312, Lok 252
Defining Member functions of Class
Templates
• template <class Any> • cout<<"Stack Overflow!!";
• class Stack{ • }
• Any arr[4]; • template <class Any>
• int top; • void Stack<Any>::pop( ){
• public: • if(top>=0){
• Stack( ); •
• void pop( ); cout<<"Popping..."<<endl;
• void push( Any); • top--;
• void display( ); • }
• }; • else
• cout<<"Stack is
• template <class Any> Empty!!";
• Stack<Any>::Stack( ) • }
{ • template <class Any>
• top=-1; • void Stack<Any>::display(
• } ){
• if(top<0){
• template <class Any> • cout<<"Stack is
• void Empty"<<endl;
Stack<Any>::push(
Any x){ • return;
• if(top<4) • }
• (East),
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri cout<<"Stack elements
Mumbai 400 059. www.pragatisoftware.com 253