C++ Programming Pragati Software Pvt. Ltd. www.pragatisoftware.com
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
1 195.01.03
Table of Contents Module 1: Getting Started Module 2: Arrays Module 3: Functions Module 4: Pointers and References Module 5: Classes and Objects Module 6: Friend Keyword Module 7: Operator Overloading Module 8: Inheritance Module 9: Polymorphism and Abstract classes Module 10: Streams Module 11: File I/O Module 12: Exception Handling Module 13: RTTI and Casting Operators Module 14: Templates
5 63 77 104 132 168 173 184 199 208 218 224 236 247
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
2
C++ Programming Developed by : Bjarne Stroustrup Where : Bell Telephone Laboratories When : 1979 Influenced by: C Influenced : C#, Java
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
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 ”<
Syntax: cout<<“string”; cout<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
8
Standard Input Consider the statements cin rel="nofollow">> var1; cin>>x>>y;
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 • Fundamental data types in C++ Type Integer Character Floating Point Double precision floating point Boolean
Keyword int char float double bool
• 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 TC++
SIZE (Bytes) for 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 short int unsigned short int
2
2
2
2
long int or signed long int unsigned long int
4
4
4
4
float
4
4
double
8
8
10
10
long double
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
11
Variables & Constants • Variable – a physical entity which can be changed E.g. height, weight, temperature etc.
• Constant – a physical entity which never changes E.g. pi value, number of days in a week etc.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
12
Variables • • •
All variables must be declared before being used. In C++ variables can be declared anywhere in the code. A variable may be initialized with a value while declaring it, by using the ‘=’operator
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’;
Syntax for declaration datatype v1, v2, v3, …………vn; datatype u1=value1,u2,u3=value2…;
where v1, v2, v3 are variable names.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
14
The ‘sizeof’ operator Consider the statements cout<<sizeof (int); cout<<sizeof x;
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' '\t' '\r' '\b' '\a' '\\' '\’'
new line horizontal tab carriage return backspace 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…
1. /*Program to demonstrate use of constants*/ 2. int main ( ) 3. { 4. int num1=10; /*10 is an integer constant */ 5. double num2=28.5; /*28.5 is a floating point constant */ 6. char c = 'W'; /* ‘W’ is a character constant */ 7. cout<<"This is a constant string."; 8. cout<<"\nThe value of num1="<< num1; 9. cout<<"\nThe value of num2="<< num2; 10. cout<<"\nThe character "<
19
Defining Symbolic Constants Consider the statement: # define PI 3.14159
Syntax: # define symbolic_name value
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="<
21
The Constant Variables • Variables of type (qualifiers) const cannot be changed by the program. • However, it can be given an initial value. • Used as a READ ONLY variable. 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
: + - ++ -- + - * / % : = , += -= *= /= %= : > < >= <= == != : && || ! : & | ^ << >> ~
Also classified into : Unary
: &(addr) *(indirect) +(sign) –(sign) ~(complement) !(NOT) ++(incre) --(decre) Binary : All other operators listed above Ternary : Conditional operator(? :)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
23
Increment and Decrement Operators An increment operator (++) adds 1 to its operand. A decrement operator (--) subtracts 1 from its operand. i ++; ++i; i --; --i;
/* i = i + 1 (post fixed) */ /* i = i + 1 (prefixed) */ /* i = i - 1 (post fixed) */ /* i = i - 1 (prefixed) */
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; i *= 5; i /= 5;
/* Subtract 5 from i */ /* Multiply i with 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 2. using namespace std; 4. int main( ) 5. { 6. int fahr=100, celsius; 7. celsius= 5*(fahr-32)/9; 8. cout<
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; Pragati Software Pvt. 15. }Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
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
Statement1
True
If 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
Statement1
True
If condition
False Statement2
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; if ((percentage>=40) && (percentage<50)) cout<<“Third division”;
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) Statement
if(condition) { Statements }
if(condition) Statement else Statement
if(condition) { Statements } 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: exp1 ? exp2 : exp3
If exp1 evaluates to true, then exp2 is returned else exp3 is returned
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"<
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<
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. 2. 3. 4.
int main ( ) { int a=4,b=4; char ch; 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 :"<
39
The switch statement Syntax: switch ( integer expression) { case constant1: statements; case constant2: statements; case constant3: statements; default: statements; }
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 rel="nofollow">>ch; switch(ch) { case 'a': case 'e': case 'i': case 'o': case 'u': cout<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
42
Iteration • The while loop • The do-while loop • The for loop
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
43
The while loop Start
while condition
false Exit loop
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 Consider the statements while(i<=10) while(i>=1) while(i<=10 && j<=15)
Syntax: while (expression) statement;
while (expression) { statement1; statement2; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
45
Using while • • • • • •
#include using namespace std; int main( ) { int i; i=1;
• • • • • • •
while(i<=10) { cout<<“\nValue of i is :”<
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 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 "<>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
true
while condition
false
Exit loop 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{ statement; while (expression);
statement1; statement2; } while (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 2. using namespace std; 3. int main( ) 4. { 5. int i; 6. i=1; 7. do 8. { 9. cout<<"\nValue of i is : "<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
50
The for loop Start
for condition
false Exit loop
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…
Consider the statements for(i=0;i<5;i++) for(i=10;i>=0;i--)
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 using namespace std; int main( ) { int i; for(i=0;i<=10;i++) cout<<"\nValue of i is : "<
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 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<
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 using namespace std; int main( ) { int i; for(i=1;i<=20;i++) { if(i%14==0) break; cout<<<"\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 using namespace std; int main( ) { int i; for(i=1;i<=20;i++) { if(i%2!=0) continue; cout<<"\nValue of i is : "<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
57
Using ‘goto’ • • • • • • • • • • • • •
#include 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. 2. 3. 4. 5. 6. 7. 8.
#include using namespace std; int main( ) { float result = 4 / 3; cout<
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 1. 2. 3. 4. 5. 6. 7. 8.
contd…
#include using namespace std; int main( ) { float result= (float) 4/3; cout<<"Result = "<
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: datatype ArrayVariableName[ number of elements] ;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
64
Array example • • • • • • • • • • • • • • • • •
#include 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"<
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 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 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}; Index number Or subscript
Values
0
1
2 3
4
5
score 89 125 56 45 0 0 100
102
104
106
108 110
6 0
7 0
112 114
8
9 10
0 116
0 118
0 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
R o
s
y
\0
100
101 102
5
6
7
8
103 104 105 106 107 108
9
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: int strlen (const char *source); char *strcpy(char *destination, const char *source); char *strcat(char *Destination, char *Source); int strcmp (const char *string1, const char *string2);
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 Consider the statement int student[5][2];
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: "<
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” };
Index
100
0
M o
n
d
a
y
\0
1
T u
e
s
d
a
y
\0
2
W e
d
n
e
s
d
a
y
3
T h
u
r
s
d
a
y
\0
4
F
r
i
d
a
y
\0
5
S
a
t
u
r
d
a
6
S
u
n
d
a
y
\0
110
\0
120
Memory Locations
130 140
y
\0
150 160
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 :"<
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 • Set of statements written in a separate body • To perform a distinguishable task • Functions are classified into 1) Library or built-in functions 2) User defined functions
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
78
Library functions • Library or built-in functions eg. strcpy( ), strcat( )
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 Return type
Function name
int isEven value)
Formal Parameter list (int
{ if(value % 2 == 0) return 1; else return 0; }
Function body
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
81
Function types • Without argument & without return value void clrscr(void);
• With argument but no return value void gotoxy(int x, int y);
• With argument & with return value int abs(int num);
• Without argument but with return value int getchar( );
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<<<"\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 the position of declaration in the program Storage class. 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 function
Available to the entire program, hence can be shared by other functions
Are lost as soon as the declaring function body terminates • void fun( ) • { • int i=10; /*local to fun */ • } • void foo( ) • { • int i=10; /*local to foo */ • }
Are lost as soon as the declaring application or program terminates • int k=10; /* global to prg */ • void fun( ) • { • int i=10; k=35; • } • void foo( ) • { • int i=10; cout<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
85
Storage Classes The storage class gives the following information about the variable: Where it is stored Its initial value Scope of variable Lifetime of the variable i.e. how long it exists
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 2. using namespace std; 4. void inc( ); 5. void inc_i( ); 7. int 8. { 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. }
main( ) cout<<"Invoking function inc( )...."; inc( ); inc( ); inc( ); cout<<"Invoking function inc_i( )...."; inc_i( ); inc_i( ); inc_i( ); return 0;
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:"<
• • • • •
void inc_i( ){ static int i; /* static variable */ i++; cout<<"\nValue of 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 F04GlobalVar.cpp */ 2. int n = 3; 3. void alter ( ); 4. int main ( ) 5. { 6. cout<< n; 7. alter( ); 8. cout<< n; 9. return 0; 10. }
1. /* Source file F04ExternExample.cpp */ • • • • •
extern int n; void alter ( ) { n = 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 static int array [MAX]; int array2 [20]; int main ( ) { ... } static int privatefun ( ) { ... } double publicfun ( ) { ... } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
94
Recursion • Function makes a call to itself • Repeatedly invokes itself until a condition is met • Hence must have a return statement to exit
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 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 "<
96
Default Arguments Eg: cin.ignore(1); & cin.ignore(4,’\n’); square(6); & square(6, 10);
Syntax: return_type func_name( arg1, arg2, …., argn = value){ //executable statements; }
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<
• • •
int add(int x,int y){ return x+y; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
98
Function overloading void void void void
max (int, int); max (float, float); max (char , char); max (int, int, int);
Function calls will be: max(87, 65); max( 35.5f, 76.6f); max( ‘J’, ‘L’); max(45, 90, 23);
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 1. void add(int x,int y=15){ 2. cout<<x+y<<endl; 3. } 4. void add(int x,int y){ 5. cout<<x+y<<endl; 6. } 7. int main( ){ 8. add(13); 9. add(10,10); 10. return 0; 11. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
101
Inline functions • To avoid the run-time overhead when using functions Eg: inline int min (int v1,int v2){ return (v1 < v2 ? v1 : v2 ); }
• Syntax inline return_type function_name (argument_list){ //executable statements; }
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 • Variable which holds a only memory address pointer variable = 65524
Name
Num
Value
189
Memory address
65524
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 Type of that variable whose address will be stored by the pointer
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 : pointerVariableName = & variable; 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; 5.
cout<<"Value of x:"<<x<<endl; 6. cout <<"Value at *ptr:"<<*ptr<<endl; 7. cout <<"Value at &x:"<<*&x<<endl<<endl;
65514 65516 65518
65520
9.
cout <<"Address of x:"<<(unsigned)( &x)<<endl; 10. cout <<"Address pointed by the pointer:"<<(unsigned)ptr<<endl ;
65522
65524
65524
ptr
30
z
20
y
10
x
12. cout<<"Changing the contents at address pointed by ptr... Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
108
Pointer example
contd…
1. cout<<"Changing the ptr address ... "<<endl; 2. ptr=&y; 3. cout<<"Value of y:"<
65514
65516
6. cout <<"Address of x:"<<(unsigned)(&y)<<endl; 7. cout <<"Address pointed by the pointer:"<<(unsigned)ptr<<endl; 8. 9. cout<<"The size of the pointer is:"<<sizeof(ptr)<<endl; 10. return 0; 11. }
65518
65524
ptr
30
z
65522
20
y
65524
10
x
65520
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. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
int main ( ){ int ary[5]={10,20,30,40,50}; int *ptr, i; for(i=0;i<5;i++){ ptr=&ary[i]; cout<<*ptr<<'\t'; } cout<< endl<<"Size of pointer:"<<sizeof(ptr); cout<<endl<< "Size of array:"<<sizeof(ary)<<endl; return 0; 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 • Operations allowed on pointers Pointer and integer addition Pointer and integer subtraction Pointer and pointer subtraction Pointer and pointer relational operations
• Operations NOT allowed on pointers Pointer and pointer addition All division and multiplication operations
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. 2. 3. 4. 5. 6. 7.
int main( ){ int ary[5]={10,20,30,40,50}; int *ptr,*ptr1=ary; for(ptr=ary;ptr<&ary[5];ptr++){ cout<<*ptr; } cout<<“Number of elements in the array are:”<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
115
Example of pointer subtraction 1. 2. 3. 4. 5. 6. 7. 8.
/* Function to find the length of a string. */ int str_len (char *s) { char *p = s; while (*p != '\0') p ++; return (p - s); }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
116
Pointers as function arguments • Two methods to call a function with arguments Call by Value Call by reference
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’<
• • • • • •
void swap(int num1, int num2) { int temp; temp=num1; num1=num2; num2=temp; }
// 10 20 // 10 20
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’<
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(int x, int y)
swap(&x,&y); swap(int *x, int *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 ptr[0]=ary1; ptr[1]=ary2; ptr[2]=ary3; for(i=0;i<3;i++) cout<<(ptr[0]+i) ; cout<< endl; for(i=0;i<5;i++) cout<<(ptr[1]+i) ; cout<< endl; for(i=0;i<7;i++) cout<<(ptr[1]+i) ; cout<< endl; return 0; } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
123
Array of pointers to character strings int main ( ) { int num; cout<<“Enter month number "; cin rel="nofollow">>num; cout<<"The month name is :“<<month (num) ; return 0; } char *month (int n) { char *name[ ] = {"Illegal month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return ( (n < 1 || n > 12) ? name [0] : name [n] ); }
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( ) { int x=10; int *ptr1=&x;
65516
int **ptr2 = &ptr1;
65518
int ***ptr3 = &ptr2; cout<<***ptr3; return 0; }
65514
65520 65522
65524
65520
ptr3
65522
ptr2
65524
ptr1
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 /* Program to type command line strings */ int main (int argc, char *argv [ ] ) { int i; for (i = 1; i < argc; i ++) cout<<“arg “<<<“is :“<< argv [i] ; }
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<<“ & ”<
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: data_type & reference_variable = variable;
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: "<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
130
Using References 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.
int look_up (const int *array, int size, int value, int &occurs){ int index = -1; for (int ix = 0; ix < size; ++ix) if(array [ix] == value){ if (index == -1) index = ix; ++occurs; } return index; } int main( ){ int arry[]={10,24,10,35,62,10,24},no_elements=0; int position=look_up(arry,(sizeof arry)/(sizeof(int)),35,no_elements); if(position==-1) cout<<"Number is not in the array"<<endl; else{ cout<<"Position:"<<position<<endl; cout<<"No of occurances:"<<no_elements<<endl; } return 0; }
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-"<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
134
Access Specifiers • private : Members are accessible within the class only. They are not inherited by the derived class. • public :
Members are accessible anywhere. They are also inherited by the derived classes.
• protected : Members are accessible in the class itself & also inherited by the derived classes
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
135
Using Access Specifiers • class BankAccount { //default access is private. • unsigned acc_num; • double balance; • public: • void deposit(double amt){ • balance+=amt; • } • void withdraw(double amt){ • balance-=amt; • } • void display( ){ • cout<<"Account NUMBER-"<
136
Using the member functions 1. int 2. { 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. }
main( ) BankAccount ba; ba.display( ); ba.deposit (5000); cout<<"Balance after depositing Rs.5000/- :"; ba.display( ); ba.withdraw(1000); cout<<"Balance after withdrawing Rs.1000/- :" ; ba.display( ); return 0;
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. 2. 3. 4. 5. 6. 7. 8.
#include using namespace std; class X { public: int count; }; int X::count = 10; // define data member
10. 11. 12. 13. 14.
int main ( ) { int X = 0; // hides class type X cout << X::count << endl; // use member of class X return 0; }
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. 2. 3. 4. • • • •
class BankAccount { unsigned acc_num; double balance; public: void setdata ( unsigned , double) void deposit(double); void withdraw(double); void display( ); };
• • •
void BankAccount :: withdraw(double amt) { balance-=amt; }
• • •
void BankAccount :: deposit(double amt) { balance+=amt; }
• •
void BankAccount :: display( ) { cout<<"Account NUMBER-"<
139
this pointer void BankAccount :: setdata ( unsigned acc_num, double balance) { this → acc_num = acc_num; this → balance = balance; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
140
Constructors • Automatic initialization done with special member function called Constructors i.e., • Constructor is executed automatically whenever an object is created. • Constructors have, Same name as class No return type • Constructors can take arguments • Constructors can be overloaded
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); •
Syntax to define a constructor 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 ( ) { constructor min_bal = 5000; acc_num = 2004; }
// default
Using the member initialization list : 5. BankAccount ( ) : min_bal( 5000 ) , acc_num( 2004 ) 6. { }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
145
Parameterized constructor (unsigned x) : min_bal ( 5000 ) , acc_num ( x ) { }
BankAccount
(double bal,unsigned x) : min_bal (bal) , acc_num(x) { }
BankAccount
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-"<
147
Constructor Overloading
Contd …
• • • •
int main( ){ BankAccount B1; B1.deposit(3500); B1.display( );
•
BankAccount B2(3005); //BankAccount B2=3005; B2.deposit(8000); B2.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) //{ } BankAccount (unsigned x ,double bal=5000):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 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-"<
Explicit keyword
Contd …
1. int main( ){ 2. BankAccount B2=3005; //error 3. B2.deposit(8000); 4. cout<<"\nB2 details...."<<endl; 5. B2.display( ); 7. 8. }
return 0;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
151
Copy constructor • Used to declare and initialize an object from another object Syntax to declare: class_name ( class_name &); Syntax to invoke c’tor: class_name new_object = source_object; 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-"<
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( );
• • •
BankAccount B2(B1); // invoking copy ctor cout<<"\nB2 cloned B1...."<<endl; B2.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 • Used to allocate memory to objects at runtime • Memory can be allocated using the new operator Eg: int *pi=new int; int *pia = new int[10]; LinkList *ptr = new LinkList( );
• Memory can be de-allocated using the delete operator delete ptr
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<
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- rel="nofollow">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 • Automatically called when an object is destroyed . • 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<
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; 7. 8. 9. 10. }
cout<<endl<<"For temporary object"<<endl; BankAccount B1(334,4500); return 0;
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: static data-type data_member;
Syntax to assign a value: Outside the class: data-type ClassName :: data_member = value;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
161
Static Member functions • Can access only other static members of the same class Syntax to declare: return_type static function_name(argument_list) ; 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:"<
163
Static Data Members and Member Functions Example • • • • •
void display( ){ cout<<"\nAccount NUMBER-"<
• • • •
int main( ){ BankAccount S1; S1.deposit( 3500 ); S1.display( );
•
BankAccount S2(451,3005); // BankAccount S2=3005; • S2.deposit( 8000 ); • S2.display( ); • BankAccount::showNoObjects( ); • cout<<endl; • return 0; Pragati • Software } Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
164
Const Objects and const Member functions • • • • • • • • • • • • • • • • • •
class Time{ int hr,min,sec; 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 { cout<<endl<<"the time is:"; cout<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
165
Const Objects and const Member functions •
Time const noon (12,0,0 ) ; object
• • • • • • •
int main( ) { noon.display( ); noon.setTime(5,6,7); cout<<endl; return 0; }
//Const
//will be an error ;
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<
};
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 nonmember functions Syntax for declaring: friend return_type function_name(argument list); Syntax for defining: function_name(argument list){ // Body of function } Syntax for calling: 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<
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:"<
• • • • • •
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 • Facility to give mutiple meaning to the set of predefined operators. • Syntax for declaring return_type operator operator_symbol(argument_list);
• Syntax for defining return_type operator operator_symbol(argument_list){ }
• Syntax for calling class_object1 operator_symbol class_object2; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
174
Operator Overloading • The following operators can be overloaded: + ^ += < rel="nofollow"> &&
= -= <= ||
* < & >= ++
/ > new << --
% != delete >> ()
Following operators cannot be overloaded: sizeof, . , :: , ?: Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
175
Operator Overloading • Operator Overloading can be done by two methods: As a member function As a friend function
• No of parameters a Unary operator takes If declared as a member function is none If declared as a friend function is one
• No of parameters a Binary operator takes If declared as a member function is one If declared as a friend function is two
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<
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 n; sec){ • • this->hr= hr; result.sec=t1.sec+t2.sec; • this->min= min; • return result; • this->sec= sec; • } • } • void display( ){ • cout<
Operator Overloading Example The call for both methods: • • • • • • • • •
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{ • Time 2. int hr, min, sec; operator++( ) 3. public: • { 4. Time( ) • Time result; 5. { • result.hr=++hr; 6. hr=0; • 7. min=0; result.min=++min; 8. sec=0; • 9. } result.sec=++sec; 10. Time (int hr, int min, int sec) { • return result; 11. this->hr=hr; • } 12. this->min=min; • }; 13. this->sec=sec; 14. } 15. void display( ){ 16. cout<
Overloading the Prefix operator as a Friend function • • • • • • • • • • • • • • • • • •
class Time{ int hr, min, sec; public: Time( ){ hr=0; min=0; sec=0; } Time( int hr, int min, int sec){ this->hr= hr; this->min= min; this->sec= sec; } void display( ){
cout<
• • • • • • • •
Time operator++ (Time t) { Time result; result.hr=++t. hr; result.min=++t. min; result.sec=++t. sec; return result; }
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: • • • • • • •
Time operator++ ( int){ Time result; result. hr= hr++; result. min= min++; result. sec= sec++; return result; }
As a friend function: • • • • • • •
Time operator++ (Time t, int){ Time result; result. hr=t. hr++; result. min=t. min++; result. sec= t. sec++; return result; }
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 • Creating a new class from an existing class • Syntax: class derived_class_name: access specifier baseClass_name { …… };
• Syntax for Multiple Inheritance class derived_class_name: access specifier baseClass1_name, access specifier baseClass2_name, … { …… Pragati Software Pvt. Ltd., 312,}; Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
185
Inheritance Access Specifier Type of Access Specifier private
PRIVATE MEMBERS
PROTECTED MEMBERS
PUBLIC MEMBERS
Not Inherited
Inherited but become private members of derived class
Inherited but become private members of derived class
protected
Not inherited
Inherited but remain protected members of derived class
Inherited but become protected members of derived class
public
Not inherited
Inherited but remain protected members of derived class
Inherited but become public members of derived class
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:"<
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. 7. }
return 0;
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);
3. • • • •
class BankAccount { BankAccount( ) { accNo=0; balance=5000; } };
• • • • •
class SavingAccount : public BankAccount { SavingAccount(float rofI) { rateOfInterest=rofI; } };
invokes
invokes
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{ protected: char typeOfMembership; public: Membership( ) {} Membership(char type) { typeOfMembership=type; } void display() { cout<<"\nThe Membership is of
class SavingAccount { static float minimumBalance; float rateOfInterest; public: SavingAccount( ) {} SavingAccount(float rofI) { rateOfInterest=rofI;
} void display( ) { cout<<"\nThe rate of Interest applied is:"<
Multiple Inheritance • • • • • • • •
Contd…
class LoanAccount: public Membership, public SavingAccount { }; int main( ) { LoanAccount B1; B1.display( ); error! return 0; }
//Ambiguity
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:"<
Polymorphism Example int main( ) { BankAccount B1(203,10000.0); BankAccount *Baseptr=&B1; Baseptr- rel="nofollow">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 • No actual objects are created from it. • A class in C++ is abstract if it contains at least one pure virtual function • A virtual function equated to zero is called a pure virtual function
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:"<
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 A stream is a general name given to a flow of data in an input/output situation. Streams are called iostreams in C++ 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 ostream
istream iostream ifstream
ofstream fstream
istream_ withassign
iostream_ withassign
ostream_ withassign
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
210
Reading strings • Syntax
cin.get(signed char *s,int n,char_delim='\n');
cin.getline(signed char *s,int n,char_delim='\n')
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 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. 2. 3. 4. 5. 6. 7. 8. 9.
#include #define MAX 20 int main( ) { char str1[MAX]; cout<<"Enter a string: "; cin.getline(str1,MAX,'.'); cout<<str1<<"\n"; }
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 2. { 3. 4. 5. 6. 7. 8. 9. 10. 11.}
main( ) char str[30]; int code; cout<<"Enter the code of the Employee "; cin>>code; cout<<"Enter the name of the Employee "; cin.getline(str,30); cout<<str<<" has code:"<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
214
cin.ignore( ) • Extract and discard characters • Eg : cin.ignore(4,'\n'); cin.ignore(1); Syntax: istream& ignore ( streamsize n = 1, int delim = EOF );
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 2. { 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. }
main( ) char str[30]; int code; cout<<"Enter the code of the Employee "; cin>>code; cin.ignore(4,'\n'); cout<<"Enter the name of the Employee "; cin.getline(str,30); cout<<str<<" has code:"<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
216
Manipulators •Special functions used to alter format parameters Manipulator
Parameter
endl
function ‘\n’
setprecision
Number of decimal digits to be displayed
precision
setfill
Fill character
fill
setw
Variable width
width
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 • File stream classes declared in fstream in the namespace std ifstream Used for file input operations Derived class of istream 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 • Two ways to open a file: using open function using the constructor • 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 #include 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<
221
Reading/Writing an object to a File #include #include 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<
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)); cout<<"\nData read is..."<<endl; P2.displayData(); cout<<endl; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
223
Module 12: Exception Handling • 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 • Runtime Errors are called exceptions • C++ exception handling has three keywords: try catch throw
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 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:"<
228
Re-throwing an exception void func1( ) { try{ throw "SOMETHING went wrong !!!"; } catch ( const char *s){ cout<<"Inside internal handler !!"<<endl; cout<<"\n Rethrowing the exception to the calling function..."; throw; } }
int main( ) { try{ func1( ); } catch(const char *s){ cout<<"\nBack in function main !!"<<endl; cout<<s<<endl; } }
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( ) { int num; try{ cout<<"Enter a number \n"; cin>>num; if(num<0) throw MyException("Not a positive number !!",num); else cout<<"The number is a positive number:"<
230
Handling derived class exceptions class A{ }; class B{ }; //class C inherits from B and A class C: public B, public A{ }; C c; B b; A a;
int main( ) { try{ throw c;
} catch (C d) { cout <<"\n Catch of derived \n \n"; } catch ( B &a){ cout<<"\n Catch of base b \n"; } catch ( A &){ cout<<"\n Catch of base a\n"; } } Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
231
Unwinding the stack class Employee{ int acc_no; char name[10]; public: Employee(int x,char *str){ acc_no=x;
int main( ) { try{ Employee emp(1,"Sunil"); cout<<"\nException generated..."; throw 1; } catch ( int){ strcpy(name,str); cout<<"\n In Exception } Handler"<< endl; ~Employee( ){ } cout<<"\nIn the } destructor"; } };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
232
Throwing exceptions from constructors class Engineer{ public: Engineer( ){ cout<<"Inside } ~Engineer( ){ cout<<"Inside } }; class Manager{ public: Manager( ){ cout<<"Inside } ~Manager( ){ cout<<"Inside } };
Engineer constructor !!"<<endl; Engineer destructor !!"<<endl;
Manager constructor !!"<<endl; Manager destructor !!"<<endl;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
233
Throwing exceptions from constructors Contd… class EngineerManager : public Manager{ public: EngineerManager ( ){ cout<<"Inside EngineerManager constructor !! "<<endl; Engineer e; throw -1; } ~EngineerManager ( ){ cout<<"Inside EngineerManager destructor !! "<<endl; } }; int main( ){ try{ EngineerManager EM; } catch(int){ cout<<"CAUGHT AN ERROR"<<endl; } Pragati}Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
234
Using set_terminate ( ) function void Big_crunch ( ){ cout<<"UNEXPECTED ERROR IN APPLICATION !! "<<endl<< “Exiting to os"<<endl; exit(-1); } 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 • RTTI: Run Time Type Identification. • This allows to identify object-type during program execution. • Syntax: typeid(object); • Uses #include returns a reference to an object of type type_info. • type_info is a class that describes the type of object and defines the following public members: • typeid
bool operator ==(const type_info &ob); bool operator !=(const type_info &ob); bool before(const type_info &ob); const char *name( );
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
237
typeinfo class #include #include using namespace std; class ClsBase{ virtual void func( ){ cout<<"In base class"; } }; class class2{ }; class ClsDerv:public ClsBase{ void func( ){ cout<<"HI"; } }; Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
238
Using typeid int main( ){ int i,j; float f; char * chp; ClsBase obj1,*ptr=0; class2 obj2; ClsDerv d1,*dptr=0; cout<<"Data type of int i is:"<
239
Using typeid if(typeid(i)==typeid(j)) cout<<"\nBOTH i and j are integers and of the same type"<<endl; if(typeid(i)==typeid(f)) cout<<"BOTH i and f are of the same type"<<endl; else cout<<"i and f are not the same type"<<endl; cout<<endl; 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; cout<<"\nThe number preceding the name indicates the number of characters in the class name "<<endl; cout<<"The type of obj1 is:"<
240
Using typeid cout<<"The type of obj1 is:"<
241
Casting Operators • Explicit Casting operators • Syntax: cast_name (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 { public: virtual void display( ) { cout<<"In base"; } }; class Derived:public Base { public: void display( ) { cout<<"In Derived"; } };
void main( ){ Base *bp; Derived *dp, d; bp = &d; if(!bp) cout<<"Casting failed"; dp = dynamic_cast(bp); if(!dp) cout<<"Casting failed"; else cout<<"Dynamic casting successful !!”; }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
243
const_cast • • • • • •
int square ( const int *val){ int *ptr; ptr = const_cast ( val); *ptr = *val * *val; return *ptr; }
• • • • • •
int main( ){ int num=5; cout<<"Number:"<
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<
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 (ptr); cout<<"add value:"<
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 • Syntax for Function Template: template ret-type func-name ( parameter list) { // body of function }
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 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: "<
249
Template Function with two arguments • • • • • • • • • • • • • • • • •
template void display(TY a,TB b){ cout<
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
250
Class Template • #include • #include<string> • using namespace std;
1. void pop( ){ 2. if(top>=0) { 3. cout<<"Popping..."<<endl; • template 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--) Pragati Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com • Software} 16.
251
Class Template
• cout<<"Stack of strings....."<<endl; • int main( ) • Stack<string> S2; • { • S2.push("Hi"); • cout<<"Stack of • S2.push("Hello"); Integers....."<<endl; • S2.push("What's"); • Stack S1; • S2.display( ); • S1.push(3); • S2.pop( ); • S1.push(33); • S2.display( ); • S1.push(111); • cout<<"Pushing element ........."<< • S1.display( ); • S2.push("UP!!"); • S1.pop( ); • S2.display( ); • S1.display( ); • cout<<"Popping 3 elements : "<<e • cout<<"Pushing • 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( ); • } Pragati Pvt. Ltd., 312, Lok 252 • SoftwareS1.pop( );Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com
Defining Member functions of Class Templates • template • • class Stack{ • Any arr[4]; • int top; • public: • Stack( ); • void pop( ); • void push( Any); • void display( ); • };
• • • • •
cout<<"Stack Overflow!!"; } template void Stack::pop( ){ if(top>=0){
cout<<"Popping..."<<endl; • top--; • } • else • cout<<"Stack is • template Empty!!"; • Stack::Stack( ) • } { • template • top=-1; • void Stack::display( • } ){ • if(top<0){ • template • cout<<"Stack is • void Empty"<<endl; Stack::push( • return; Any x){ • } • if(top<4) Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri Mumbai 400 059. www.pragatisoftware.com • (East), cout<<"Stack elements
253