100% found this document useful (1 vote)
124 views

Programming in C++ - 195.01.03

Service Access & Configuration Patterns The Wrapper Facade design pattern encapsulates the functions and data provided by existing non-object-oriented APIs within more concise, robust, portable, maintainable, and cohesive object-oriented class interfaces. The Component Configurator design pattern allows an application to link and unlink its component implementations at run-time without having to modify, recompile, or statically relink the application. Component Configurator further supports the reconfiguration of components into different application processes without having to shut down and re-start running processes. The Interceptor architectural pattern allows services to be added transparently to a framework and triggered automatically when certain events occur. The Extension Interface design pattern allows multiple interfaces to be exported by a component, to prevent bloating of interfaces and breaking of client code when developers extend or modify the functionality of the component. Event Handling Patterns The Reactor architectural pattern allows event-driven applications to demultiplex and dispatch service requests that are delivered to an application from one or more clients. The Proactor architectural pattern allows event-driven applications to efficiently demultiplex and dispatch service requests triggered by the completion of asynchronous operations, to achieve the performance benefits of concurrency without incurring certain of its liabilities. The Asynchronous Completion Token design pattern allows an application to demultiplex and process efficiently the responses of asynchronous operations it invokes on services. The Acceptor-Connector design pattern decouples the connection and initialization of cooperating peer services in a networked system from the processing performed by the peer services after they are connected and initialized.

Uploaded by

hiscasio
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
124 views

Programming in C++ - 195.01.03

Service Access & Configuration Patterns The Wrapper Facade design pattern encapsulates the functions and data provided by existing non-object-oriented APIs within more concise, robust, portable, maintainable, and cohesive object-oriented class interfaces. The Component Configurator design pattern allows an application to link and unlink its component implementations at run-time without having to modify, recompile, or statically relink the application. Component Configurator further supports the reconfiguration of components into different application processes without having to shut down and re-start running processes. The Interceptor architectural pattern allows services to be added transparently to a framework and triggered automatically when certain events occur. The Extension Interface design pattern allows multiple interfaces to be exported by a component, to prevent bloating of interfaces and breaking of client code when developers extend or modify the functionality of the component. Event Handling Patterns The Reactor architectural pattern allows event-driven applications to demultiplex and dispatch service requests that are delivered to an application from one or more clients. The Proactor architectural pattern allows event-driven applications to efficiently demultiplex and dispatch service requests triggered by the completion of asynchronous operations, to achieve the performance benefits of concurrency without incurring certain of its liabilities. The Asynchronous Completion Token design pattern allows an application to demultiplex and process efficiently the responses of asynchronous operations it invokes on services. The Acceptor-Connector design pattern decouples the connection and initialization of cooperating peer services in a networked system from the processing performed by the peer services after they are connected and initialized.

Uploaded by

hiscasio
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 253

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 195.01.03
1
Table of Contents

 Module 1: Getting Started 5


 Module 2: Arrays 63
 Module 3: Functions 77
 Module 4: Pointers and References 104
 Module 5: Classes and Objects 132
 Module 6: Friend Keyword 168
 Module 7: Operator Overloading 173
 Module 8: Inheritance 184
 Module 9: Polymorphism and Abstract classes 199
 Module 10: Streams 208
 Module 11: File I/O 218
 Module 12: Exception Handling 224
 Module 13: RTTI and Casting Operators 236
 Module 14: Templates 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 <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

Consider the statements


cin>> 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 Keyword
Integer int
Character char
Floating Point float
Double precision floating point double
Boolean 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 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

• 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' 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…

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 "<<c<<" has an ASCII code
of "<<(int)c;
11. cout<<endl;
12. return 0;
13. }
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 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="<<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

• 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 + 1 (post fixed) */


++i; /* i = i + 1 (prefixed) */
i --; /* i = i - 1 (post fixed) */
--i; /* 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; /* 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;

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) 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:

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"<<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:

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>>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

• 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

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

Consider the statements


while(i<=10)
while(i>=1)
while(i<=10 && j<=15)

Syntax:

while (expression) while (expression)


statement; {
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 <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…

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 <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:

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<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};

Index number Or subscript


Values

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:

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: "<<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

• 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 Formal Parameter list

int isEven (int


value)

{
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

• 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<<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 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 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

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<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

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<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:

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<<add(10,20)<<endl;
• cout<<add(8)<<endl;
• return 0;
• }

• 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 max (int, int);


void max (float, float);
void max (char , char);
void 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;
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

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:"<<y<<endl;
65514
4. cout <<"Value at
*ptr:"<<*ptr<<endl<<endl;
65516

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

• 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. 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

1. /* Function to find the length of a string. */


2. int str_len (char *s)
3. {
4. char *p = s;
5. while (*p != '\0')
6. p ++;
7. return (p - s);
8. }

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’<<y; // 10 20
• swap(x,y);
• cout<<x<<‘\t’<<y; // 10 20
• return 0;
• }

• void swap(int num1, int num2) {


• int temp;
• temp=num1;
• num1=num2;
• num2=temp;
• }

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);

swap(int x, int 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>>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( )
{
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

/* Program to type command line strings */


int main (int argc, char *argv [ ] )
{
int i;
for (i = 1; i < argc; i ++)
cout<<“arg “<<i<<“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<<“ & ”<<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:

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: "<<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

• 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-"<<acc_num<<":"<<"\nRs "<<balance<<"\n";
• }
• };
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 136
Using the member functions
1. int main( )
2. {
3. BankAccount ba;
4. ba.display( );
5. ba.deposit (5000);
6. cout<<"Balance after depositing Rs.5000/- :";
7. ba.display( );
8. ba.withdraw(1000);
9. cout<<"Balance after withdrawing Rs.1000/- :" ;
10. ba.display( );
11. return 0;
12. }

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

10. int main ( ) {


11. int X = 0; // hides class type X
12. cout << X::count << endl; // use member of class X
13. return 0;
14. }

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( );
• };

• void BankAccount :: withdraw(double amt) {


• balance-=amt;
• }

• void BankAccount :: deposit(double amt) {


• balance+=amt;
• }

• void BankAccount :: display( ) {


• cout<<"Account NUMBER-"<<acc_num<<":"<<"\nRs
"<<balance<<"\n";
• Software
Pragati } Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 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 ( )
{ // default
constructor
• min_bal = 5000;
• acc_num = 2004;
• }

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

BankAccount (unsigned x) : min_bal ( 5000 ) ,


acc_num ( x )
{ }

BankAccount (double bal,unsigned x) : min_bal


(bal) , acc_num(x)
{ }

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( );

• 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<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

• 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-"<<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( );

• 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<<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

• 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<<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;

7. cout<<endl<<"For temporary object"<<endl;


8. BankAccount B1(334,4500);
9. return 0;
10. }

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:"<<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( );

• BankAccount S2(451,3005); // BankAccount


S2=3005;
• S2.deposit( 8000 );
• S2.display( );
• BankAccount::showNoObjects( );
• cout<<endl;
• return 0;
• Software
Pragati } 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<<hr<<":"<<min<<":"<<sec;
• }
• };
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 ) ; //Const
object

• 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

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<<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

• 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:

+ - * / %
^ = < > !=
+= -= & 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<<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

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{
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:

• Time operator++ • Time operator++


( int){ (Time t, int){
• Time result; • Time result;
• result. hr= • result. hr=t.
hr++; hr++;
• result. min= • result. min=t.
min++; min++;
• result. sec= • result. sec= t.
sec++; sec++;
• return result; • 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 PRIVATE PROTECTED PUBLIC
Access MEMBERS MEMBERS MEMBERS
Specifier
private Not Inherited Inherited but Inherited but
become private become private
members of members of
derived class derived class
protected Not inherited Inherited but Inherited but
remain protected become protected
members of members of
derived class derived class
public Not inherited Inherited but Inherited but
remain protected become public
members of members of
derived class 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:"<<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. }

10. void display( ){


11. //invoking methods of other classes
12. BankAccount::display( );
13. cout<<"\nThe rate of Interest applied
is:"<<rateOfInterest<<endl;
14. }
15. };

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);

3. class BankAccount { invokes


BankAccount( ) {
• accNo=0;
• balance=5000;
• }
• }; invokes

• class SavingAccount : public BankAccount {


• SavingAccount(float rofI) {
• rateOfInterest=rofI;
• }
• };

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…

• class LoanAccount: public Membership, public


SavingAccount
• { };

• 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…

class SavingAccount : class Membership :


public virtual BankAccount public virtual BankAccount
{ {
float minimumBalance; protected:
float rateOfInterest; char
typeOfMembership;
public:
public:
SavingAccount( )
Membership( )
{} {}
SavingAccount (int AccNo, Membership(char
double bal, type)
float {
rofI):BankAccount(AccNo,bal)
{ typeOfMembership=type;
rateOfInterest=rofI; }
};
}
};
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 197
Hybrid Inheritance Contd…

class LoanAccount : public Membership, public


SavingAccount
{ };

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

virtual return_type function_name(argument list);

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

• 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:"<<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

 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

istream ostream

iostream
ifstream ofstream
fstream

istream_ iostream_ ostream_


withassign withassign 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<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( )

• 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 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

•Special functions used to alter format parameters

Manipulator Parameter function

endl ‘\n’

setprecision Number of decimal precision


digits to be displayed
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<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));

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<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

class MyException{ int main( ) {


int num;
public:
try{
char msg[80]; cout<<"Enter a
int value; number \n";
MyException(){ cin>>num;
*msg=0; if(num<0)
value=0; throw
} MyException("Not a positive
MyException(char number !!",num);
*str,int what){ else
strcpy(msg,str); cout<<"The number is a
value=what; positive number:"<<num;
}
}
catch(MyException e){
}; cout<<e.msg<<":";
cout<<e.value;
}
cout<<endl;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 230
Handling derived class exceptions

class A{ }; int main( )


class B{ }; {
//class C inherits from B try{
and A throw c;
}
class C: public B, public catch (C d) {
A{ }; cout <<"\n Catch of
C c; derived \n \n";
B b; }
A a; 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; int main( )
{
char name[10];
try{
public: Employee emp(1,"Sunil");
Employee(int x,char cout<<"\nException
*str){ generated...";
acc_no=x; throw 1;
}
strcpy(name,str); catch ( int){
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 constructor !!"<<endl;
}
~Engineer( ){
cout<<"Inside Engineer destructor !!"<<endl;
}
};
class Manager{
public:
Manager( ){
cout<<"Inside Manager constructor !!"<<endl;
}
~Manager( ){
cout<<"Inside 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<typeinfo.h>

• typeid 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:
 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<iostream>
#include<typeinfo>
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:"<<typeid(i).name()<<endl;


cout<<"Data type of int j is:"<<typeid(j).name()<<endl;
cout<<"Data type of float f
is:"<<typeid(f).name()<<endl;
cout<<"Data type of pointer chp
is:"<<typeid(chp).name()<<endl;
cout<<"Data type of *chp
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 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:"<<typeid(obj1).name( )
<<endl;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 240
Using typeid
cout<<"The type of obj1 is:"<<typeid(ptr).name( )
<<endl;
cout<<"The type of obj2 is:"<<typeid(dptr).name( )
<<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;

cout<<"Data type of ptr is:"<<typeid(ptr).name()<<endl;


cout<<"Data type of dptr
is:"<<typeid(dptr).name()<<endl;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 241
Casting Operators

• Explicit Casting operators

• 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 square ( const int *val){


• int *ptr;
• ptr = const_cast<int*> ( val);
• *ptr = *val * *val;
• return *ptr;
• }

• 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 = &num;
• cout<<"num address:"<<(int)&num;
• 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

• Syntax for Function Template:

template <class Ttype> 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<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

You might also like