Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

NOTES

Download as ppsx, pdf, or txt
Download as ppsx, pdf, or txt
You are on page 1of 275

C++

Programming
Index
Chapter 1. Object Oriented Programming
Chapter 2. Introduction To CPP
Chapter 3. Classes & Objects
Chapter 4. Functions In CPP
Chapter 5. Constructor & Destructor
Chapter 6. Inheritance
Chapter 7. Virtual Functions
Chapter 8. Operator Overloading & Type Conversion
Chapter 9. Introduction To C++ I/O System
Chapter 10. Exception Handling
Chapter 11. Templates
Chapter 12. File Handling
Chapter No. 1
Object Oriented Programming
Software Evolution

Characteristics Of Procedure Oriented Programming

Characteristics Of Object Oriented Programming

OOPS Concepts

Benefits & Advantages Of OOPS

Dalcomp Technologies 3
Software Evolution

1,0 Binary
Machine Language
Assembly Language

Procedure Oriented Programming

Object Oriented Programming

Dalcomp Technologies Layers of Computer Software 4


Characteristics of Procedure Oriented
Programming

 Emphasis is on doing things.

 Large Programs are divided into smaller programs known as

functions.

 Most of the functions share global data.

Dalcomp Technologies 5
Characteristics of Procedure Oriented
Programming

 Data move openly around the system from function to function.

 Functions transform data from one form to another.

 Employs top – down approach in program design.

Dalcomp Technologies 6
Characteristics of Object Oriented
Programming
 Emphasis is on data rather than procedure.

 Programs are divided into what are known as objects.

 Data structures are designed such that they characterize the

objects.

 Functions that operate on the data of an object are tied

together in the data structure.

Dalcomp Technologies 7
Characteristics of Object Oriented
Programming
 Data is hidden & cannot be accessed by external functions.

 Objects may communicate with each other through functions.

 New data & functions can be easily added whenever necessary.

 Follows bottom up approach in program design.

Dalcomp Technologies 8
OOPs Concepts

Object :-
1. Objects are the basic run time entities in an object oriented
system.
2. They may represent a person, a place, a table, a bank account, a
table of data or any item that the program has to handle.
3. For ex:- If “Customer” & “Account” are two objects in a
program, then the customer object may send a msg to the acct
object requesting for the bank balance.

Dalcomp Technologies 9
Class :-
1. We just mentioned that objects contain data, & code to
manipulate that data, the entire set of data & code of an
object can be made a user defined data type with the
help of a Class.
2. For Ex.
Mango, Apple & Orange are the members of class
fruit.
3. If the fruit has been defined as a class , then the
statement
fruit mango;
will create an object mango belonging to the class fruit.
Dalcomp Technologies 10
Data Abstraction :-

1. Abstraction is the process of extracting the relevant

properties of an object while ignoring nonessential

details.

2. The extracted properties define a view of the object.

3. Classes use the concept of abstraction & are defined as a

list of abstract attributes such as size, weight & cost &

functions to operate on these attributes.


Dalcomp Technologies 11
Example Of Data Abstraction
4. For Ex. A car dealer might view a car from the standpoint of its
selling features. Relevant properties include price, color, optional
equipment, and length of warranty.

On the otherhand, a mechanic views the car from the


standpoint of the systems that require maintainance. Here relevant
properties include the type of oil, the size of the oil filter, and the
number and type of spark plug. The properties of a car relevant to
a car dealer are different from the properties relevant to a
mechanic. By focusing on the relevant properties and ignoring
irrelevant details, the complexity of dealing with an object is
reduced.
Dalcomp Technologies 12
Data Encapsulation:-
1. The binding of code and data into single unit called class is
known as Data Encapsulation.

2. The data is not accessible to the outside world & only those
functions which are bind inside the class can access it.

3. These functions works as the interface between the objects


data & code.

Dalcomp Technologies 13
4. Writing data and code into the single unit class is known as

Data Hiding .

For Ex:- Medical Capsule i.e. One drug is stored in bottom

layer & another drug is stored in upper layer these 2 layers are

combined in single capsule.

Dalcomp Technologies 14
Polymorphism:-
1. Polymorphism means “many forms and one interface”.
2. It allows us to have many function with the same name inside a
class.
Polymorphism

Compile Time Run-Time


(Static Binding) (Dynamic Binding)

Virtual
Operator Function Functions
Overloading Overloading
e.g. cin>>n; e.g. int add(int, int);
C = a>>2; Float add(float, int);

For Ex:- A man can be a Father, Son ,Husband, Employee & Good Citizen.
15
Inheritance:-

1. It is the process by which object of one class acquires the


property of object of another class, it support concept of hierarchy
classification.
2. In OOPS, inheritance provide the idea of reusability. i.e. reusing
the properties of superclass into its sub class .
3. We can add new properties or data to an new subclass.
4. For Ex. Father & son relationship.
Student

R no, Name Base Class Data Members


get(), put() Base Class Methods

Inheritance(Extending class)

Marks
Sub 1, Sub 2 Derived Class Data Members
get() , put() Derived Class Methods
Dalcomp Technologies 16
Dynamic Binding:-

1. Binding refers to the linking of a procedure call to the code


to be executed in response to the call.
2. Dynamic Binding (also known as late binding) means that the
code associated with a given procedure call is not known until
the time of the call at run time.
3. We see the Polymorphism example:-

Shape
Draw()

Circle Object Triangle Object


Box Object
Draw(Circle) Draw(Box) Draw(Triangle)

4. For Ex. In the given figure, for draw() method ,at run time, the
code matching the object under current reference will be called.
Dalcomp Technologies 17
Message Passing:-

1. An object oriented program consists of a set of objects that communicate


with each other.
2. Objects communicate with one another by sending & receiving
information much the same way as people pass message to one another.

For Ex:-

Employee.Salary(name);

Object Information
Message

Dalcomp Technologies 18
Benefits Or Advantages of OOPS
1. Through inheritance, we can eliminate redundant code & extend the use of

existing classes.

2. We can build programs from the standard working modules that communicate

with one another rather than having to start writing the code from scratch. This

leads to saving of development time & higher productivity.

3. The principle of data hiding helps the programmer to build secure programs

that cannot be invaded by code in other parts of the program.

Dalcomp Technologies 19
4. It is possible to have multiple instances of an object to co-

exist without any interference.

5. Object oriented systems can be easily upgraded from small

to large systems.

6. Message Passing techniques for communication between

objects makes the interface descriptions with external systems

much simpler.

7. Software complexity can be easily managed.


Dalcomp Technologies 20
End Of Chapter 1
Any Question?

Home
Dalcomp Technologies 21
Chapter No. 2
Introduction To C++
 Introduction
 Difference between C & C++
 First Program of C++
 Introduction to Classes
 Scope Resolution Operator
 Memory Management Operator
 Difference between dynamic memory allocation in C & C++
 Reference Variable

Dalcomp Technologies 22
Introduction

1. C++ is an Object Oriented Programming Language.

2. It was developed by Bjarne Stroustrup at AT & T Bell


laboratories in New Jersey, USA in 1980’s as a successor of
‘C’.

3. To overcome drawbacks of ‘C’ Language Stroustrup


combine the features of Simula 67 & c into new languages
called ‘C with Class’.

4. This Language is renamed to ‘C++’ in 1983.

Dalcomp Technologies 23
Difference Between C & C++
1. C follows the procedural programming paradigm while C++ is a multi
paradigm language(procedural as well as object oriented)

In case of C, importance is given to the steps or procedure of the


program while C++ focuses on the data rather than the process.
Also, it is easier to implement/edit the code in case of C++ for the same
reason.

2. In case of C, the data is not secured while the data is


secured(hidden) in C++.

Dalcomp Technologies 24
Difference Between C & C++
3. C is regarded as a low-level language(difficult interpretation &
less user friendly) while C++ has features of both low-
level(concentration on whats going on in the machine
hardware) & high-level languages(concentration on the
program itself) & hence is regarded as a middle-level
language.
4. C uses the top-down approach while C++ uses the bottom-up
approach

5. C is function-driven while C++ is object-driven


Dalcomp Technologies 25
Difference Between C & C++
6. C++ supports function overloading while C does not

7. We can use functions inside structures in C++ but not in C.

8. C++ allows the use of reference variables while C does not

9. C contains 32 Keywords,C++ extends it to 52 Keywords

10. C++ is a superset of C while C is a superset of B.

Dalcomp Technologies 26
First program of c++

 // my first program in C++


#include <iostream.h>
int main ()
{
cout << "Hello world!";
return 0;
}

Dalcomp Technologies 27
Scope Resolution Operator
This Operator is used for:-
void test :: getdata()
1. To unhide the global variable that
{
might have bought hidden by
local variables. x=10;y=20;
2. To access members declared in }
class scope. void main()
{
For Ex:- class test test s;
{ s.getdata();
int x,y; s.disp();
public: void getdata(); getch();
void disp() }
{
Output:-
cout<<x<<“\t”<<y;
} 10 20
};
Dalcomp Technologies 28
Example of Scope Resolution Operator to access global variables:-
#include<iostream.h>

int m = 10; // global m

void main()
{
int m =20; // m local to main
Output:-
{ We are in inner block
int k = m; k = 20
int m = 30; // m declared again m= 30
::m = 10
cout<<“We are in inner block\n”; We are in outer block
cout<<“k=“<<k<<“\n”; m = 20
cout<<“m=”<<m<<“\n”; ::m = 10
cout<<“::m=” << ::m << “\n”;
}
cout<<“n We are in outer block \n”;
cout<<“m=”<<m<<“\n”;
cout<<“::m=“ << ::m<<“\n”;
getch();
Dalcomp Technologies 29
}
Memory Management Operator
C++ Provides two operators for dynamic memory allocation &
deallocation:-

1) new operator :- This operator is used to allocate memory


for data element of any type.
Syntax : data type pointer = new datatype; or
data type pointer = new type[size];
e.g. int *p;
p = new int; or p = new int[5];

Dalcomp Technologies 30
2)delete operator :- When the memory allocated dynamically is

no longer in use must be free so that it becomes available for

future request of dynamic memory this can be done using

delete operator.

Syntax : delete pointer; or delete [] pointer

e.g. delete p; e.g. delete [] p;

Dalcomp Technologies 31
Difference between memory management in c & c++
Memory management in C Memory management in C++
1. Dynamic memory management is 1. Dynamic memory management is
done using function like done using operators new &
malloc(),calloc,realloc & free. delete.
2. Fuctions require additional time. 2. Operators execute faster.
3. We have to include header file to 3. No need of any header file.
use this function.
4. The allocated memory can be
4. The allocated memory can only initialize to any value.
be initialize to 0.
5. The operators can be overloaded
5. This functions can not be in c++.
overloaded in c.

Dalcomp Technologies 32
Reference Variables

 A reference variable is a new name given to an existing variable.

 It is alice of the original variable.

 The reference variable cannot exist independently i.e. It can

only refer to an existing variable.

Dalcomp Technologies 33
Reference Variables

No memory is allocated to the reference variable.

The original name & reference name both refers to the

same memory location.

The value can be access or change using either the original

name or reference name.

Dalcomp Technologies 34
Example of reference variable

#include<iostream.h>
void main()
{
int x= 10;
clrscr();
cout<<“Value of x:”<<x;
int &rx = x; // reference variable
Value of x: 10
cout<<“Value of x:”<<rx; Value of x: 10
rx = rx + 5; Value of x: 15
cout<<“Value of x:”<<x;
getch();
}

Dalcomp Technologies 35
End Of Chapter 2
Any Question?

Home
Dalcomp Technologies 36
Chapter No. 3
Classes And Objects
 Declaration & Syntax Of Class & Object
 Access Specifiers In Class
 Creating Object
 Defining Member Functions
 Private Member Function
 Arrays Within a Class
 Static Class Members
 Friend Functions

Dalcomp Technologies 37
Definition & Syntax of Class & Object
 A class is an expanded concept of a data structure: instead of

holding only data, it can hold both data and functions.

 An object is an instantiation of a class. In terms of variables, a

class would be the type, and an object would be the variable.

 Classes are generally declared using the keyword class, with the

following format:

Dalcomp Technologies 38
 class class_name
{
access_specifier_1 :
data type variable_name ;
access_specifier_2 :
data type member2;
access _specifier
data type method name(){ } ;
...
} object_names;

Dalcomp Technologies 39
Example of Class
#include <iostream>
class CRectangle {
int x, y; //data member or data variables
public:
void set_values (int,int); // member functions
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
int main () {
CRectangle rect; //obj declaration
rect.set_values (3,4);
cout << "area: " << rect.area();
Area : 12
return 0;
}

Dalcomp Technologies 40
Creating Object

 Here cRectangle rect; creates a variable rect of type cRectangle.


Class variable is known as Objects.
We may also declare more than one object in 1
statement.

For Ex:- cRectangle rect,rect1,rect2;


 Accessing Class Members:-
Syntax: object_name.function_name(actual_arguments);

For Ex:- x.getdata(100,75.5);

Dalcomp Technologies 41
Defining Member Functions
1. Outside The Class Definition
2. Inside The Class Definition
1. Outside Class Definition:-
Syntax:
return_type class_name::fun_name(arg_declaration)
{
Function Body;
}

Dalcomp Technologies 42
Access Specifiers
 private members of a class are accessible only from within other
members of the same class or from their friends.

 protected members are accessible from members of their same


class and from their friends, but also from members of their
derived classes.

 public members are accessible from anywhere where the object


is visible.

Dalcomp Technologies 43
Defining Member Functions
2. Inside The Class Definition
Syntax:- return_type function_name(arg.decln)
{
function body;
}

Dalcomp Technologies 44
Example of Defining Member Function Outside
class Box
double Box::getVolume(void)
{
{return length * breadth * height; }
public: double length;

double breadth; void Box::setLength( double len )

double height; { length = len; }


double getVolume(void);
void Box::setBreadth( double bre )
void setLength(double len);
{ breadth = bre; }
void setBreadth( double bre );

void setHeight( double hei );

};

Dalcomp Technologies 45
void Box::setHeight( double hei )
volume = Box1.getVolume();
{ height = hei; }
cout << "Volume of Box1 : " << volume
int main( )

{ Box Box1; <<endl;

Box Box2; volume = Box2.getVolume();


double volume = 0.0; cout << "Volume of Box2 : " << volume
Box1.setLength(6.0);
<<endl; return 0;
Box1.setBreadth(7.0);
}
Box1.setHeight(5.0);

Box2.setLength(12.0); Volume of Box1: 210


Volume of Box2 : 1560
Box2.setBreadth(13.0);

Box2.setHeight(10.0);
Dalcomp Technologies 46
Example Of Defining Member Function
Inside
class item void main()
{ {
int number; item x;
float cost; cout<<“Item x:”<<“\n”;
public:
void getdata(int a,int b) x.getdata(100,299.95);
{number = a; cost = b;} x.putdata();
void putdata(void) getch();
}
{
cout<<number;
Item x:
cout<<cost; 100
} 299.95
};
Dalcomp Technologies 47
Member function have some special
characteristics
 Several different classes can use the same function name. The
‘membership label’ will resolve their scope.

 Member Function can access the private data of the class. A


non member function cannot do so.(However an exception to
this rule is a friend function.)

 A member function can call another member function directly,


without using dot operator.

Dalcomp Technologies 48
Making an outside function inline

 One of the objective of OOP is to separate the details of


implementation from the class definition, therefore it is good to
define the member function outside the class.

 It is done by just using the word inline in the header of


function definition.

Dalcomp Technologies 49
Inline Function
 C++ inline function is powerful concept that is commonly used with classes.

If a function is inline, the compiler places a copy of the code of that function

at each point where the function is called at compile time.

 To inline a function, place the keyword inline before the function name and

define the function before any calls are made to the function. The compiler

can ignore the inline qualifier in case defined function is more than a line.

 A function definition in a class definition is an inline function definition,

even without the use of the inline specifier.

Dalcomp Technologies 50
Example Of Making An Outside Function Inline
 Example:
class item
{
......
......
public:
void getdata(int a,float b);
};
inline void item :: getdata(int a,float b)
{
number=a;
cost=b;
}

Dalcomp Technologies 51
Example Of Inline Function :-
#include<iostream.h>

class line
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
};
Dalcomp Technologies 52
void main()
{ line obj;
float val1,val2;
clrscr();
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:"<<obj.mul(val1,val2);
cout<<"\n\nCube value is :"<<obj.cube(val1)<<"\t"<<obj.cube(val2);
getch();
} Output:
Enter two values: 5 7
Multiplication Value is: 35
Cube Value is: 25 and 343

Dalcomp Technologies 53
Private Member Functions
Public:
 The private member function are not
void show()
directly accessible outside the class, {
we can access them in public disp();
member function of same class & cout<<“show”;
that function is accessible outside the }
};
class.
void main()
{
 Class test
{ test s;
void disp() s.show();
{ getch(); display show
cout<<“display”; }
}

Dalcomp Technologies 54
Arrays within a class
 The arrays can be used as member variables in a class. The
following class definition is valid.

For Ex. Const int variable[size];

 Class array
{
int a[size]; // a is int type array
public:
void setval(void);
void display(void);
};
Dalcomp Technologies 55
Example Of Arrays within Class:-

#include<iostream.h>

const int m = 50;

class items
{
int itemCode[m];
float itemPrice[m];
int count;
public:

void CNT(void){
count = 0;
} //initializes count to 0
void getitem(void);
void displaySum(void);
void remove(void);
void displayItems(void);
};Dalcomp Technologies 56
void items :: getitem(void) // assign values to data
{
cout<<“Enter item code:”;
cin>>itemCode[count];
cout<<“Enter item cost:”;
cin>>itemPrice[count];
count++;
}
void items :: displaySum(void) //display total value of all items
{
float sum = 0;
for(int i=0;i<count;i++)
sum = sum + itemPrice[i];
cout<<“\n Total value:”<<sum<<“\n”;
Dalcomp Technologies 57
}
void items :: remove(void) //delete a specified item
{
int a;
cout<<“Enter item code:”;
cin>>a;
for(int i=0;i<count;i++)
if(itemCode[i] == a)
itemPrice[i] = 0;
}

void items :: displayItems(void) //displaying items


{
cout<<“\n Code Price\n”;
for(int i=0;i<count;i++)
{
cout<<“\n”<<itemCode[i];
cout<<“ ”<<itemPrice[i];
}
}

Dalcomp Technologies 58
int main()
{
items order;
order.CNT();
int x;

do // do…….while loop
{

cout<<“\n You can do the following:”;


cout<<“\n Enter the appropriate number:”;
cout<<“\n 1 : Add an item”;
cout<<“\n 2 : Display total Value”;
cout<<“\n 3 : Delete an item”;
cout<<“\n 4 : Display all items”;
cout<<“\n 5 : Quit”;
cout<<“\n What is your Option?”;

cin >> x;

Dalcomp Technologies 59
switch(x)
{
case 1: order.getitem();break;
case 2: order.displaySum();break;
case 3: order.remove();break;
case 4: order.displayItems(); break;
case 5: break;
default : cout <<“Error in input; try again\n”;
}
} while (x != 5); //do … while ends
return 0;
}

Dalcomp Technologies 60
Output:
You can do the following : Enter appropriate number
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 1
Enter item code : 111
Enter item cost : 100

You can do the following : Enter appropriate number


1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 1
Enter item code : 222
Enter item cost : 200
Dalcomp Technologies 61
You can do the following : Enter appropriate number
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 1
Enter item code : 333
Enter item cost : 300

You can do the following : Enter appropriate number


1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 2
Total value : 600

Dalcomp Technologies 62
You can do the following : Enter appropriate number
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 3
Enter item code : 222

You can do the following : Enter appropriate number


1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 4
code price
111 100
222 0
Dalcomp Technologies
333 300 63
You can do the following : Enter appropriate number
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 5

Dalcomp Technologies 64
Static Class Members

1. Static Data Member:-


(To share the memory area)
 It is initialized to 0 when the first object of its class is created.
No other initialization is permitted.
 Only one copy of that member is created for the entire class &
is shared by all the objects of that class, no matter how many
objects are created.
 It is visible only within the class ,but its lifetime is the entire
program .Static variables are normally used to maintain values
common to the entire class.

Dalcomp Technologies 65
Example of Static Data Member
 Class test
{
public:
static int a;
void disp()
{cout<<“\n\t”<<a;}
};
int test :: a=10;
void main()
{
test s1;
S1.disp();
Output: 10
test s2;
s2.disp();
10
getch();
}

Dalcomp Technologies 66
Another Example Static Data Members:-
#include<iostream.h>
class item
{ a.getcount();
static int count; b.getcount();
int number; c.getcount();
Public:
void getdata(int a) a.getdata(100);
{ b.getdata(200);
number = a; c.getdata(300);
count++;
} cout<<“After reading data”<<“\n”;
void getcount(void)
{ a.getcount();
count : 0
cout<<“Count:”; b.getcount();
c.getcount(); count : 0
cout<<count<<“\n”;
count : 0
}
getch(); After reading data
};
int item :: count;
} Count : 3
Count : 3
void main()
Count : 3
{
item a,b,c;
Dalcomp Technologies 67
Static Class Members
Static Member Functions:-
 A static member function can have access to only other static
members declared in the same class.

 A static member function can be called using the class name


(instead of its objects) as follows:

 Class_name :: function_name;

Dalcomp Technologies 68
Example of Static Member Function
 Class test
{
public:
static void disp()
{ cout<<“display”;}

};
void main()
{
clrscr();
display
test :: disp();
getch();
}

Dalcomp Technologies 69
Another Example of Static Member Functions:-
#include<iostream.h>
Class test
{
int code;
static int count;
public :
void setcode (void)
{
code = ++count;
}
void showcode(void)
{
cout<<“Object number:”<<code<<“\n”;
}
static void showcount(void)
{
cout<<“count:” <<count<<“\n”;
}
};
Dalcomp Technologies 70
int test :: count;
int main()
{
test t1,t2;

t1.setcode();
t2.setcode();
Count : 2
test :: showcount();
Count : 3
Object number:1
test t3; Object number:2
t3.setcode(); Object number:3

test :: showcount();

t1.showcode();
t2.showcode();
t3.showcode();

return 0;
} Dalcomp Technologies 71
Friend Functions
 The private members cannot be accessed from outside the class. i.e. a
non-member function cannot have an access to the private data of a
class.

 However ,there could be a situation where we would like two classes


to share a particular function.

 In this situation,c++ allows the common function to be made friendly


with both the classes.

 To make outside function “friendly” to a class, just declare the


function as a friend of the class.

Dalcomp Technologies 72
Characteristics of friend function:-

 It is not in the scope of the class to which it has been declared as

friend.

 Since it is not in the scope of the class, it cannot be called using the

object of that class.

 It can be invoked like a normal function without the help of any

object.

Dalcomp Technologies 73
Characteristics of friend function:-

Unlike member function, it cannot access the member names

directly & has to use an object name & dot membership operator

with each member name.

It can be declared either in the public or the private part of a class

without affecting its meaning.

Usually, it has the objects as arguments.

Dalcomp Technologies 74
Example of friend function
class sample
{
int a;
int b;
public:
void setvalue()
{ a = 25; b = 40 ; }
friend float mean(sample s);
};
Float mean(sample s)
{
return float(s.a + s.b) / 2.0;
}

Dalcomp Technologies 75
Example of friend function
void main()
{
sample x;
x.setvalue();
cout<<“Mean value =” <<mean(x)<<“\ns”;
}

Output : Mean
Value = 32.5

Dalcomp Technologies 76
A Function Friendly to two classes
#include<iostream.h>
class ABC;
class XYZ
{
int x;
public:
void setvalue(int i) { x = i ;}
friend void max(XYZ,ABC);
};
Class ABC
{
int a;
public:
void setvalue(int i){a = i;}
friend void max(XYZ,ABC);
};
Dalcomp Technologies 77
void max(XYZ m,ABC n)
{
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}
int main() 20
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc); //friend function called as normal function
return 0 ;
}

Dalcomp Technologies 78
Returning Objects
A Function cannot only receive objects as arguments but also can return them.
The example illustrates how an object can be created (within a function) and
returned to another function.

#include<iostream.h>
class complex // x+iy form
{
float x; // real part
float y; // imaginary part
public:
void input(float real, float imag)
{ x = real; y = imag; }
friend complex sum(complex, complex);
void show (complex);
};
Dalcomp Technologies 79
complex sum(complex c1, complex c2) int main()
{ {
complex c3; //object c3 is created complex A,B,C;
c3.x = c1.x + c2.x; A.input(3.1,5.65);
B.input(2.75,1.2);
c3.y = c1.y + c2.y;
c = sum(A,B); // C = A + B
return (c3); // returns object c3 cout<<“A = “; A.show(A);
} cout<<“B = “; B.show(B);
void complex :: show(complex c) cout<<“C= “; C.show(c);
{ return (0);
}
cout<<c.x<<“+j”<<c.y<<“\n”;
}
}
A = 3.1 + j5.65
B = 2.75 + j1.2
C = 5.85 + j6.85

Dalcomp Technologies 80
End Of Chapter 3
Any Question?

Home
Dalcomp Technologies 81
Chapter No. 4
Functions In C++
 Introduction To Function
 Advantages Of Function
 Function Call Methods
 Remarks on Functions
 Local vs Global Variables
 Function Overloading
 Inline Function

Dalcomp Technologies 82
Introduction To Function

 A function is a group of statements that together perform a task.

 A function declaration tells the compiler about a function's

name, return type, and parameters. A function definition

provides the actual body of the function.

Dalcomp Technologies 83
Introduction To Function

 The C++ standard library provides numerous built-in functions


that your program can call.

Syntax of Function Definition:

return_type function_name( parameter list )

body of the function

Dalcomp Technologies 84
Advantages Of Functions

 Functions allow to reuse the code.

 With the help of function we can differentiate the tasks.

 Functions helps to design, debug & maintain a program.

Dalcomp Technologies 85
Function Call Methods
 Call by value

A copy of the value is passed

 Call by reference

The caller passes the address of the value

Dalcomp Technologies 86
Function Call Methods
 Call by value
 Up to this point all the calls we have seen are call-by-value, a copy of the value
(known) is passed from the caller-function to the called-function

 Any change to the copy does not affect the original value in the caller function

 Advantages, prevents side effect, resulting in reliable software

 Call By Reference
 We introduce reference-parameter, to perform call by reference. The caller
gives the called function the ability to directly access the caller’s value, and to
modify it.
 A reference parameter is an alias for it’s corresponding argument, it is stated
in c++ by “flow the parameter’s type” in the function prototype by an
ampersand(&) also in the function definition-header.
 Advantage: performance issue

87 Dalcomp Technologies
Function Call Methods
void function_name (type &);// prototype

main()
{
-----
------
}
void function_name(type *parameter_name)

88 Dalcomp Technologies
Function Call Example
passing parameters by reference:
#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c) // using reference variables


{
a*=2;
b*=2;
c*=2;
}

int main ()
{ x=2, y=6, z=14
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
89 Dalcomp Technologies
compute square and cube of numbers [1..10] using functions
#include<iostream.h>

int square(int); // prototype


int cube(int); // prototype
main()
{ int i;
for (int i=1;i<=10;i++){

cout<< i<< “square=“ << square(i) << endl;


Output
cout<< i<< “cube=“ <<cube(i) << endl;
1 square=1
} // end for
1 cube=1
return 0;
2 square=4
} // end main function
2 cube=8
int square(int y) //function definition
.
{
.
return y*y; // returned Result
.
}
.
10 square=100
int cube(int y) //function definition
10 cube=1000
{
return y*y*y; // returned Result
90 Dalcomp Technologies
}
// Finding the maximum of three floating-point (real) numbers.
#include <iostream.h>
double maximum( double, double, double ); // function prototype
int main()
{
double number1, number2;
Function maximum takes 3
double number3;
arguments (all double) and
returns a double.
cout << "Enter three real numbers: ";
cin >> number1 >> number2 >> number3;

// number1, number2 and number3 are arguments to the maximum function call
cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl;
return 0;

}
// function maximum definition. x, y and z are parameters
double maximum( double x, double y, double z )
{ Enter three real numbers: 99.32
double max = x; // assume x is largest 37.3 27.1928
if ( y > max ) // if y is larger,
max = y; // assign y to max
Maximum is: 99.32
if ( z > max ) // if z is larger,
max = z; // assign z to max
Enter three real numbers: 1.1
return max; // max is largest value 3.333 2.22
Dalcomp Technologies
} Maximum is: 3.333 91
void Function takes arguments
If the Function does not RETURN result, it is called void Function

#include<iostream.h>
void add2Nums(int,int);
main()
{ int a, b;
cout<<“Enter two Number:”;
cin >>a >> b;
add2Nums(a, b) Enter two Number:
return 0; 3 5
} 3+5 = 8
void add2Nums(int x, int y)
{
cout<< x<< “+” << y << “=“ << x+y;
}

92 Dalcomp Technologies
void Function take no arguments
If the function Does Not Take Arguments specify this with EMPTY-LIST OR write
void inside
#include<iostream.h>
void funA();
void funB(void)
main()
{
funA(); Will be the same
funB(); in all cases
return 0;
}
void funA()
{
cout << “Function-A takes no arquments\n”;
}
void funB()
{
cout << “Also Function-B takes No arguments\n”;
}

93 Dalcomp Technologies
Remarks on Functions
Local variables
o Known only in the function in which they are defined
o All variables declared inside a function are local variables
Parameters
o Local variables passed to function when called ( passing-
parameters)
Variables defined outside and before function main:
o Called global variables
o Can be accessible and used anywhere in the entire program

94 Dalcomp Technologies
Local vs Global Variables
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;
x = 11;
y = 22;
cout << “global x=” << x << endl;
cout << “global y=” << y << endl;
s = add2(x, y);
cout << x << “+” << y << “=“ << s;
cout<<endl;
return 0;
} global x=11
int add2(int x1,int y1) global y=22
{ int x; //local variables Local x=44
x=44; 11+22=33
cout << “\nLocal x=” << x << endl;
return x1+y1;
}
95 Dalcomp Technologies
Function Overloading
 Function overloading

o Functions with same name and different parameters

o Should perform similar tasks


• I.e., function to square ints and function to square floats

int square( int x) {return x * x;}

float square(float x) { return x * x; }

 A call-time c++ complier selects the proper function by


examining the number, type and order of the parameters

Dalcomp Technologies 96
Example Of Function Overloading
#define pi 3.14

class fn
{
public:
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
};
void fn::area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}

Dalcomp Technologies 97
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";

cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of Triangle\n4.Exit\n:”;

cout<<”Enter your Choice:";


cin>>ch;
Dalcomp Technologies 98
switch(ch)
{ case 1:
cout<<"Enter Radious of the Circle:";
cin>>r;
obj.area(r);
break;
case 2:
cout<<"Enter Sides of the Rectangle:";
cin>>a>>b;
obj.area(a,b);
break;
case 3:
cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
obj.area(0.5,a,b);
break;
case 4:
exit(0);
}
getch();
}
Dalcomp Technologies 99
Output Of The Program
Function Overloading
1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter Your Choice: 2

Enter the Sides of the Rectangle: 5 5

Area of Rectangle is: 25

1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter Your Choice: 4

Dalcomp Technologies 100


End Of Chapter 4
Any Question?

Home
Dalcomp Technologies 101
Chapter 5
Constructors & Destructors
Introduction To Constructor

Types Of Constructor
o Default Constructor

o Parameterized Constructor

o Copy Constructor

Constructor Overloading

Destructor

Dalcomp Technologies 102


Introduction To Constructor

 It is special member function of the class.

 It has same name of class.

 It is automatically called when object(instance of class) create.

 It must be a public member.

 No Return Values.

Dalcomp Technologies 103


Types Of Constructor

 Default Constructor

 Parameterized Constructor

 Copy Constructor

 Dynamic Constructor

Dalcomp Technologies 104


Syntax Of Default Constructor
class class-name
{
Access Specifier:

Member-Variables

Member-Functions

public:

class-name()

// Constructor code

}
... other Variables & Functions

}
Dalcomp Technologies 105
Example Of Default Constructor
class Example int main()
{ {
int a,b; Example Object;
public: //Constructor
Example() // Constructor invoked.
{
Object.Display();
a=10;
b=20; return;
cout<<"Im }
Constructor"
}

void Display() Output:


{ I m Constructor
cout<<"Values :"<<a<<"\t"<<b; Values :10 20
}
}; Dalcomp Technologies 106
Types Of Constructor
Parameterized Constructor:
Which constructor has arguments thats called Parameterized Constructor.
Parameterized Constructor General Form:
class class-name
{
Access Specifier:

Member-Variables

Member-Functions

public:

class-name(type Variable,type Varibale2......)


{
// Constructor code
}
... other Variables & Functions
Dalcomp Technologies
}
Parameterized Constructor Example:
Program:
class Example
{
int a,b;
public: //Constructor Output:
Example(int x,int y) I m Constructor
{ a=x; Values 10 20
b=y;
cout<<"I m Constructor“;
}
void Display()
{
cout<<"Values :"<<a<<"\t"<<b;
}
};
int main()
{ Example Object(10,20); // Constructor invoked with parameters.
Object.Display();
return;
Dalcomp Technologies 108
}
Another Example of Parameterized constructor:

#include<iostream.h>
class integer
{
int m,n;
Public:
integer (int,int); constructor declared
void display(void)
{
cout<<“m = ”<< m << “\n”;
cout<<“n = ”<<n<<“\n”;
}
};
integer :: integer (int x,int y) constructor defined
{
m = x; n = y;
}

Dalcomp Technologies 109


int main()
{
integer int1(0,100); //constructor called implicitly
integer int2 = integer(25,75); //constructor called explicitly

cout <<“\n Object1”<< “\n”;


int1.display();

cout<<“\n Object2”<<“\n”;
int2.display();
Output:
Object1
return 0; m=0
} n = 100
Object2
m = 25
n = 75

Dalcomp Technologies 110


Copy Constructor

A copy constructor is used to declare and initialize an object


from another object.

integer (integer & i) ;


integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is known
as copy initialization.

Dalcomp Technologies 111


Copy Constructor
The statement
I 2 = I 1;
will not invoke the copy constructor.

If I 1 and I 2 are objects, this statement is legal and assigns the
values of I 1 to I 2, member-by-member.

 A reference variable has been used as an argument to the copy


constructor.

 We cannot pass the argument by value to a copy constructor.

Dalcomp Technologies 112


Example Of Copy Constructor:-
#include<iostream.h>
class code
{
int id;
public:
code(){ } // constructor
code(int a){id = a;} //constructor again
code(code &x) // copy constructor
{
id= x.id; // copy in the value
}
void display(void)
{
cout<<id;
}
};
int main()
{
code A(100); // object A is created and initialized
code B(A); // copy constructor called
code C= A; // copy constructorcalled again
Dalcomp Technologies 113
code D; // D is created, not initialized
D = A; //copy constructor not called

cout<<“\n id of A:”; A.display();


cout<<“\nid of B:”; B.display();
cout<<“\n id of C:”; c.display();
cout<<“\n id of D:”; D.display();

return 0;
}
Output:
id of A: 100
id of B : 100
id of C: 100
id of D : 100

Dalcomp Technologies 114


Dynamic Constructors
The constructors can also be used to allocate memory while creating

objects. This will enable the system to allocate the right amount of memory for

each object when the objects are not of the same size, thus resulting in the

saving of memory. Allocation of memory to objects at the time of their

construction is known as dynamic construction of objects. The memory is

allocated with the help of the new operator.

Dalcomp Technologies 115


#include<iostream.h>
class string
{
char *name;
int length;
public:
string() //constructor – 1
{
length = 0 ;
name = new char [length + 1];
}
string (char * s) // constructor 2
{
length = strlen(s);
name = new char[length+1]; // one additional character for \0
strcpy(name,s);
}
void display(void);
{ cout<<name<<“\n”; }
void join (string &a,string &b);
};
Dalcomp Technologies 116
void string :: join (string &a, string &b)
{
length = a.length + b. length;
delete name;
name = new char[length + 1]; // dynamic allocation
strcpy(name, a.name);
strcpy(name, b.name);
};
int main()
{
char *first = “Dalcomp”;
string name 1(first), name 2(“Technologies”),name3(“Chinchwad”),s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();

return 0;
Dalcomp
} Technologies 117
Output:

Dalcomp
Technologies
Chinchwad
Dalcomp Technologies
Dalcomp Technologies Chinchwad

Dalcomp Technologies 118


Constructor Overloading
 C + + permits to use more than one constructors in a single
class.

 Add( ) ; // No arguments

 Add (int, int) ; // Two arguments

Dalcomp Technologies 119


Example Of Constructor Overloading

class add  The first constructor receives


{ no arguments.
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}  The second constructor
add (int a, int b) receives two integer
{m = a ; n = b ;} arguments.
add (add & i)
{m = i.m ; n = i.n ;}  The third constructor
};
receives one add object as an
argument.

Dalcomp Technologies 120


Constructor Overloading

 C + + compiler has an implicit constructor which creates


objects, even though it was not defined in the class.

 This works well as long as we do not use any other constructor


in the class.

 However, once we define a constructor, we must also define the


“do-nothing” implicit constructor.

Dalcomp Technologies 121


Example Constructor Overloading
class rectangle
{
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
rectangle(); // another constructor
void draw(); // draw member function
void posn(int, int);// position member function
void move(int, int);// move member function
};

Dalcomp Technologies 122


Example Constructor Overloading
rectangle::rectangle() rectangle::rectangle(float a, float b)
{ {
height = 10; height=a;
width = 10; width =b;
xpos = 0; xpos =0;
ypos = 0; ypos =0;
} }

void main()
{
rectangle rc1(3.0, 2.0); //invokes parameterized constructor definition
rectangle rc2(); //invokes default constructor definition
rc1.draw();
rc2.draw();
}

Dalcomp Technologies 123


Destructor
It is a member function which deletes an object.
A destructor function is called automatically when the
object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing temporary variables ends
(4) a delete operator is called
A destructor has:
(i) the same name as the class but is preceded by a tilde (~)
(ii) no arguments and return no values

Dalcomp Technologies 124


Destructor

 It is a good practice to declare destructors in a program since it


releases memory space for further use.
 Whenever new is used to allocate memory in the constructor,
we should use delete to free that memory.
 If you do not specify a destructor, the compiler generates a
default destructor for you.
 When a class contains a pointer to memory you allocate, it is
your responsibility to release the memory before the class
instance is destroyed.

Dalcomp Technologies 125


Example Of Destructor
#include<iostream.h> void stu :: read( )
#include<conio.h> {
class stu cout<<”\n\nEnter the student Name”;
{ cin>>name;
private: char name[20],add[20]; cout<<”Enter the student roll no “;
int roll,zip; cin>>roll;
public: stu ( );//Constructor cout<<”Enter the student address”;
~stu( );//Destructor cin>>add;
void read( ); void disp( ); cout<<”Enter the Zipcode”;
}; cin>>zip;
stu :: stu( ) }
{ cout<<”These are Student
Details”<<endl; }

Dalcomp Technologies 126


Example Of Destructor
void stu :: disp( ) Void main()
{ {
cout<<”Student Name stu s;
:”<<name<<endl; s.read();
cout<<”Roll no is :”<<roll<<endl; s.disp();
cout<<”Address is :”<<add<<endl; getch();
cout<<”Zipcode is :”<<zip;
}
} Output:
These are Student Details
stu : : ~stu( )
{ cout<<”Student Details are Closed”; Enter the student Name James
Enter the student roll no 01
} Enter the student address
Newyork
Enter the Zipcode 919108

Student Name : James


Roll no is : 01
Address is : Newyork
Dalcomp Technologies Zipcode is :919108 127
End Of Chapter 5.
Any Question ?

Home
Dalcomp Technologies 128
Chapter 6
Inheritance: Extending Classes
 Introduction
 Private, Public & Protected Inheritance
 Advantages Of Inheritance
 Types Of Inheritance
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
 Virtual Base Class

Dalcomp Technologies 129


Introduction
 Inheritance is the process of creating new classes, called
derived classes, from existing classes or base classes.

 It permits code reusability.

 Reusability saves time in program development.

 With the help of inheritance we uses the code & data that is
previously defined in the base class.

Dalcomp Technologies 130


Private, Public And Protected Inheritance
 What is private, public and protected Inheritance?
 Private Inheritance
The Public and protected members of Base class become
private members of the derived class.
 Public Inheritance
All the public members and protected members are inherited
as public and protected respectively.
 Protected Inheritance
Public and Protected members are derived as protected
members.

Dalcomp Technologies 131


Advantages of Inheritance
 Reusability -- facility to use public methods of base class without
rewriting the same
 Extensibility -- extending the base class logic as per business
logic of the derived class

 Data hiding -- base class can decide to keep some data private
so that it cannot be altered by the derived class

 Overriding--With inheritance, we will be able to override the


methods of the base class so that meaningful implementation
of the base class method can be designed in the derived class.

Dalcomp Technologies 132


Types Of Inheritance
 The Class that is Pre-defined is called as Base or super Class
and the class which uses the Existing Code is known as derived
or sub class The Various Types of Inheritance those are
provided by C++ are as followings:

 1. Single Inheritance
 2. Multilevel Inheritance
 3. Multiple Inheritance
 4. Hierarchical Inheritance
 5. Hybrid Inheritance

Dalcomp Technologies 133


1. Single Inheritance
 In Single Inheritance there is only one Super Class and Only
one Sub Class Means they have one to one Communication
between them.

Base Class Or Parent Class

Derived Class Or Child Class

Dalcomp Technologies 134


Example of Single Inheritance(public):-
#include<iostream.h>
#include<conio.h>

class emp
{
public: int eno;
char name[20],des[20];
void get()
{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
Dalcomp Technologies 135
};
class salary:public emp
{
float bp,hra,da,pf,np;
public: void get1()
{ cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
Dalcomp Technologies 136
void display()
{
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<
<<np<<"\n";
}
};
void main()
{
int i,n;
char ch;
salary s[10];
clrscr();
cout<<"Enter the number of employee:";
cin>>n;
for(i=0;i<n;i++)
{
s[i].get();
s[i].get1();
s[i].calculate();
}
Dalcomp Technologies 137
cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";

for(i=0;i<n;i++)

s[i].display();

getch();

}
• /* end of program*/

Dalcomp Technologies 138


Output:
Enter the Number of employee:1
Enter the employee No: 150
Enter the employee Name: ram
Enter the designation: Manager
Enter the basic pay: 5000
Enter the HR allowance: 1000
Enter the Dearness allowance: 500
Enter the profitability Fund: 300

E.No E.name des BP HRA DA PF NP


150 ram Manager 5000 1000 500 300 6200

Dalcomp Technologies 139


Single Inheritance(Private)
#include<iostream.h>
class B
{
int a; // private; not inheritable
public:
int b; //public; ready for inheritance
void get_ab();
int get_a(void);
void show_a(void);
};
class D: private B //private derivation
{
int c;
public:
void mul(void);
void display(void);
};
Dalcomp Technologies 140
void B :: get_ab(void)
{
cout<<“Enter values for a and b:”;
cin>>a>>b;
}
int B :: get_a()
{
return a;
}
void B :: show_a()
{
cout<<“a=“ << a <<“\n”;
}
void D :: mul()
{
get_ab();
c= b * get_a(); //’a’ cannot be used directly
}

Dalcomp Technologies 141


void D: : display()
{
show_a(); //outputs value of ‘a’
cout<<“b=”<<b<<“\n”;
}
void main()
{
D d;
// d.get_ab(); won’t work
d.mul();
//d.show_a(); won’t work
d. display();
// d.b = 20; won’t work; b has become private

d.display();
getch();
}

Dalcomp Technologies 142


Output:-
Enter values for a and b: 5 10
a=5
b = 10
c= 50

Enter values for a and b: 12 20


a = 12
b = 20
c= 240

Dalcomp Technologies 143


Making a Private Member Inheritable:
 What do we do if the Private data needs to be inherited by a derived
class?
 This can be accomplished by modifying the visibility limit of the Private
member by making it Public. This would make it accessible to all the other
functions of the program, thus taking away the advantage of data hiding.
 C++ provides a third visibility modifier, Protected, which serve a limited
purpose in inheritance. A member declared as Protected is accessible by the
member functions within its class and any class immediately derived from it. It
cannot be accessed by the functions outside these two classes. A class can now
use all the three visibility modes as follow:

Dalcomp Technologies 144


class alpha
{
private: //optional
……. //visible to member functions
……. //within its class
protected:
……. // visible to member functions
……. // of its own & derived class
public:
……. //visible to all functions
……. //in the program
};

Dalcomp Technologies 145


Effects of inheritance on the
class B
visibility of members:
Not inheritable X Private X Not inheritable

Protected
class D1: public B class D2: private B
Public
Private
Private
Protected
Protected
Public class X: public D1:protected D2
Public
Private

Protected

Public
Dalcomp Technologies 146
Derived Class Visibility
Base Class visibility
Public Private Protected
derivation derivation derivation

Private Not inherited Not inherited Not inherited

Protected Protected Private Protected

Public Public Private Protected

Dalcomp Technologies 147


2.Multilevel Inheritance
 When a base class is derived by a child class which is further
derived by another child class, then it is known as Multilevel
inheritance. It can be shown using the foll. Fig.

BASE CLASS

DERIVED CLASS 1

DERIVED CLASS 2

Dalcomp Technologies 148


Example Of Multilevel Inheritance
class marks : public mm
#include <iostream.h>
{
class mm protected: int sub1;
{ int sub2;
public: void get_marks(int x,int y)
protected: int rollno;
{
public: void get_num(int a) sub1 = x;
{ rollno = a; } sub2 = y;
}
void put_num()
void put_marks(void)
{ cout << "Roll Number Is:\n"<< rollno {
<< "\n"; } cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
};
}
};
Dalcomp Technologies 149
class res : public marks int main()
{ {
protected: float tot; res std1;
public: void disp(void) std1.get_num(5);
{ std1.get_marks(10,20);
tot = sub1+sub2; std1.disp(); return 0;
put_num(); }
put_marks(); Result:

cout << "Total:"<< tot; Roll Number Is: 5


Subject 1: 10
}
Subject 2: 20
}; Total: 30

Dalcomp Technologies 150


3.Multiple Inheritance

 When more than one base classes are derived by a derived


class ,then such type of inheritance is called multiple
inheritance.

Base Class 1 Base Class 2 Base Class n

Derived Class

Dalcomp Technologies 151


Example Of Multiple Inheritance
#include <iostream.h> class Area: public Square, public
class Square Cshow
{ {
protected: int l; public: int area()
public: void set_values (int x) {
{ l=x;} return (l *l);
};
}
class CShow
};
{
public: void show(int i); int main ()
}; {
void CShow::show (int i) Area r;
{ r.set_values (5);
r.show(r.area()); Result:
cout << "The area of the square is::"
The area of the
<< i << endl; return 0; square is:: 25
} }
Dalcomp Technologies 152
4. Hierarchical Inheritance
 When one base class is inherited by more than one derived
classes,it is known as hierarchical inheritance. Each derived
class can be further inherited by other classes.

Base Class

Derived Class Derived Class Derived Class


1 2 n

Dalcomp Technologies 153


Example Of Hierarchical Inheritance
class Cube:public Side
#include <iostream.h>
{
class Side
public: int cub()
{
{ return (l *l*l); }
protected: int l;
};
public: void set_values (int x)
int main ()
{ l=x;}
{
};
Square s;
class Square: public Side
s.set_values (10);
{
cout << "The square value is::" << s.sq() <<
public: int sq()
endl;
{ return (l *l); }
Cube c;
};
c.set_values (20);
Result:- cout << "The cube value is::" << c.cub() <<
The Square Value is: 100 endl;
The cube value is : 8000 return 0;
Dalcomp Technologies } 154
5.Hybrid Inheritance
 We have seen four ways of inheriting classes: single, multilevel,
multiple and hierarchical. We can also combine these types of
inheritance and the result is known as hybrid inheritance. It can
take many forms. Two of them are shown:
Base Base
Class Class 1

Derived Derived Derived Base


Class 1 Class 2 Class 1 Class 2

Derived Derived
Class 3 Class 2

Dalcomp Technologies 155


Example Of Hybrid Inheritance
#include <iostream.h> class extra
class mm {
{ protected: float e;
protected: int rollno; public: void get_extra(float s)
public: void get_num(int a)
{e=s;}
void put_extra(void)
{ rollno = a; }
{ cout << "Extra Score::" << e << "\n";} };
void put_num()
class res : public marks, public extra
{ cout << "Roll Number Is:"<< rollno << "\n";
}}; {
protected: float tot;
class marks : public mm
public: void disp(void)
{
{ tot = sub1+sub2+e; put_num();
protected: int sub1; put_marks(); put_extra();
int sub2; cout << "Total:"<< tot; }
public: void get_marks(int x,int y) };
{ sub1 = x; sub2 = y; } int main()
void put_marks(void) { res std1; std1.get_num(10);
{ cout << "Subject 1:" << sub1 << "\n"; cout std1.get_marks(10,20);
<< "Subject 2:" << sub2 << "\n"; } }; std1.get_extra(33.12); std1.disp(); return 0;
Dalcomp Technologies
} 156
Example Of Hybrid Inheritance

 In the below example the derived class "res" uses the function "put_num()".

 Here the "put_num()" function is derived first to class "marks". Then it is


derived and used in class "res".

 This is an example of "multilevel inheritance-OOP's concept". But the class


"extra" is inherited a single time in the class "res", an example for "Single
Inheritance".

 Since this code uses both "multilevel" and "single" inheritence it is an


example of "Hybrid Inheritance".

Dalcomp Technologies 157


Output of the program:-

Result:

Roll Number Is: 10


Subject 1: 10
Subject 2: 20
Extra score:33.12
Total: 63.12

Dalcomp Technologies 158


Virtual Base Classes
A

B C

In this type of hybrid inheritance the members of class A are


accessible in class D through the classes B & C both. Hence two
copies are available which creates ambiguity. To solve this problem
we have to use virtual keyword at every place where we inherit the
base class.

Dalcomp Technologies 159


Example Of Virtual Base Class
Class Student
{
public:
int h,m,e,s,t,a; Class test : Virtual Public Student
void getmarks() {
{ public:
cout<<“Enter marks of 3 subjects:”; int te;
cin>>h>>m>>e;
void gettest()
}
{
};
Class Sports : Virtual Public Student cout<<“Enter marks of test: ”;
{ cin>>te;
public: }
void getsp() };
{
cout<<“Enter marks of sports:”;
cin>>s;
}
};
Dalcomp Technologies 160
Example Of Virtual Base Class
Class Result : Public Sports, Public Test
{
Public:
void cal()
{
t = h+m+e+s+te;
a = t / 5; Output:-
cout<<“\n Total:”<<t;
cout<<“\n Avg:”<<a; Enter marks of 3 subjects:
} 66 77 88
};
Void main() Enter marks of sports: 90
{
clrscr(); Enter marks of test: 80
result r;
Total : 401
r.getmarks();
r.getsp(); Avg : 80.2
r.gettest();
r.cal();
getch();
}
Dalcomp Technologies 161
Constructors in Derived Class

Method Of Inheritance Order of Execution


Class B: public A A(); base constructor
{ B(); derived constructor
};
Class A : public B, public C B(); base(first)
{ C();base(second)
}; A(); derived
Class A : public B, virtual public C C(); virtual base
{ B(); ordinary base
}; A(); derived

Dalcomp Technologies 162


Example Of Derived Class
#include<iostream.h>
class alpha
{
int x;
public:
alpha (int i)
{
x = i;
cout<<“alpha initialized \n”;
}
void show_x(void)
{ cout<<“x = ”<<x<<“\n”; }
};

Dalcomp Technologies 163


class beta
{
float y;
public:
beta(float j)
{
y = j;
cout<<“beta initialized \n”;
}
void show_y(void)
{ cout<<“y = ”<< y <<“\n”; }
};

Dalcomp Technologies 164


class gamma : public beta, public alpha
{
int m,n;
public :
gamma(int a, float b, int c, int d): alpha(a), beta(b)
{
m = c;
n = d;
cout<<“gamma initialized \n”;
}
void show_mn(void)
{
cout<<“m = “<<m<<“\n”<<“n = “<< n<<“\n”;
}
};

Dalcomp Technologies 165


int main()
{
gamma g(5 , 10.75 ,20,30);
cout<<“\n”;
g.show_x();
g.show_y();
g.show_mn(); OUTPUT:
beta initialized
} alpha initialized
gamma initialized

x= 5
y = 10.75

m = 20
n = 30

Dalcomp Technologies 166


End Of Chapter 6
Any Question?

Home
Dalcomp Technologies 167
Chapter No.7
Virtual Functions
 Polymorphism In C++

 Pointers To Derived Class

 Introduction To Virtual Functions

 More About Virtual Function

 Pure Virtual Function & Its Example

 Applying Polymorphism

Dalcomp Technologies 168


Polymorphism in C++

Polymorphism

Compile-time Run-time
Polymorphism Polymorphism

Function Operator
Virtual Functions
Overloading Overloading

Dalcomp Technologies 169


Polymorphism In C++

• Two types :
o Compile time polymorphism
• Uses static or early binding
• Example: Function and operator overloading
o Run time polymorphism
• Uses dynamic or late binding
• Example: Virtual functions

Dalcomp Technologies 170


Pointers To Derived Class

 C++ allows base class pointers to point to derived class objects.

 Let we have –
o class base { … };

o class derived : public base { … };

 Then we can write –


base *p1;

derived d_obj;

p1 = &d_obj;

Dalcomp Technologies 171


Example Of Pointers To Derived Class
class base { void main()
public: {
void show() { base b1;
cout << “base\n”; b1.show(); // base
} derived d1;
}; d1.show(); // derived
class derived : public base { base *pb = &b1;
public: pb->show(); // base
void show() { pb = &d1;
cout << “derived\n”; pb->show(); // base
} }
};
All the function calls here are
statically bound

Dalcomp Technologies 172


Introduction To Virtual Functions

 A virtual function is a member function that is declared within a


base class and redefined (called overriding) by a derived class.
 It implements the “one interface, multiple methods”
philosophy that underlies polymorphism.
 The keyword virtual is used to designate a member function as
virtual.
 Supports run-time polymorphism with the help of base class
pointers.

Dalcomp Technologies 173


Virtual Functions

 While redefining a virtual function in a derived class, the function


signature must match the original function present in the base class.
 So, we call it overriding, not overloading.
 When a virtual function is redefined by a derived class, the keyword
virtual is not needed (but can be specified if the programmer wants).
 The “virtual”-ity of the member function continues along the
inheritance chain.
 A class that contains a virtual function is referred to as a polymorphic
class.

Dalcomp Technologies 174


Example Of Virtual Function
class base void main()

{ { base b1;

b1.show(); // base - (s.b.)


public: virtual void show()
derived d1;
{ cout << “base\n”; }
d1.show(); // derived – (s.b.)
};
base *pb ;
class derived : public base {
pb= &b1;
public: void show() pb->show(); // base - (d.b.)
{ cout << “derived\n”; } pb = &d1;
}; pb->show(); // derived (d.b.)

} Here,

s.b. = static binding


Dalcomp Technologies 175
d.b. = dynamic binding
Example Of Virtual Function
class d2 : public base {
class base { public:
public: void show() void show()

{ cout << “base\n”; } { cout << “derived-2\n”; }

}; };

void main() {
class d1: public base {
base *pb; d1 od1; d2 od2;
public:
int n;
void show() {
cin >> n;
cout << “derived -1\n”;
if (n % 2 ==0)
} { pb = &od1;
}; else pb = &od2;

pb->show(); // guess what ??


Run-time }
Dalcomp Technologies
polymorpism 176
More About Virtual Function

 If we want to omit the body of a virtual function in a base class,


we can use pure virtual functions.
o virtual ret-type func-name(param-list) = 0;

 It makes a class an abstract class.


o We cannot create any objects of such classes.

 It forces derived classes to override it.


o Otherwise they become abstract too.

Dalcomp Technologies 177


More About Virtual Function

 Pure virtual function


o Helps to guarantee that a derived class will provide its own redefinition.

 We can still create a pointer to an abstract class


o Because it is at the heart of run-time polymorphism

 When a virtual function is inherited, so is its virtual nature.

 We can continue to override virtual functions along the


inheritance hierarchy.

Dalcomp Technologies 178


Pure Virtual Function

 A virtual function body is known as Pure Virtual Function. In

below example we can see that the function is base class never

gets invoked. In such type of situations we can use pure virtual

functions.

Syntax : Virtual type f-name(parameter-list) = 0;

Dalcomp Technologies 179


Example Of Pure Virtual Function
class base class derived2 : public base
{ {
public:
public: void show()
virtual void show()=0; //pure virtual {
function cout<<"\n Derived 2";
}; }
};
class derived1 : public base void main()
{ {
public: base *b; derived1 d1; derived2 d2;
b = &d1;
void show() b->show();
{ b = &d2;
cout<<"\n Derived 1"; b->show();
} }
}; Derived 1
Derived 2

Dalcomp Technologies 180


Final Comments

 Run-time polymorphism is not automatically activated in C++.

 We have to use virtual functions and base class pointers to


enforce and activate run-time polymorphism in C++.

Dalcomp Technologies 181


Applying Polymorphism
 Early binding
o Normal functions, overloaded functions
o Nonvirtual member and friend functions
o Resolved at compile time
o Very efficient
o But lacks flexibility
 Late binding
o Virtual functions accessed via a base class pointer
o Resolved at run-time
o Quite flexible during run-time
o But has run-time overhead; slows down program execution

Dalcomp Technologies 182


End Of Chapter 7.
Any Question ?

Home
Dalcomp Technologies 183
Chapter 8.
Operator Overloading
 Introduction

 Fundamentals Of Operator Overloading

 Operators that Can and Cannot be Overloaded

 Example Of Binary Operator Overloading

 Example Of Unary Operator Overloading

 Type Conversions

Dalcomp Technologies 184


Introduction
 It is one of the many exciting features of C++.

 C++ has ability to provide the operators with a special meaning for a data
types.

 We can overload (give additional meaning to) all the C++ operators except:
o Class member access operators ( . & .*)
o Scope resolution operators ( : : )
o Size operator (sizeof)
o Conditional operators (? : )

 When an operator is overloaded, its original meaning is not lost.

Dalcomp Technologies 185


Fundamentals Of Operator Overloading

 When operators are used with objects, then they have meaning appropriate

to those objects.

 We should use operator overloading when it makes a program clearer than

accomplishing the same operation using explicit function calls.

 When an operator is overloaded, its original meaning is not lost.

Dalcomp Technologies 186


Fundamentals Of Operator Overloading
 The overloaded operator should be used for purpose similar to its meaning.

For example, ‘+’ should be used for addition, not subtraction. Otherwise this

can make a program difficult to read.

 We can overload operators by writing a function where the function name is

formed using the keyword ‘operator’ followed by the symbol for the

operator being overloaded. For example,’operator +’ is the function name to

overload ‘+’ operator.

 Operator functions can be either members or non members of the class.

Non- member operator functions are generally friend functions of the class.
Dalcomp Technologies 187
Operators that Can and Cannot be
Overloaded
Operators that can be overloaded

+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]

Operators that cannot be overloaded

. .* :: ?:

Dalcomp Technologies 188


Example Of Binary Operator Overloading
class overloading void display()
{
{
int value;
cout<<value<<endl;
public:
void setValue(int temp) }
{ };
value = temp;
}
overloading operator+(overloading ob)
{
overloading t;
t.value=value+ob.value;
return(t);
} Dalcomp Technologies 189

int main() cout<<"Result:";
{ result.display();
overloading obj1,obj2,result;
int a,b; getch();
cout<<"Enter the value of Complex Numbers return 0;
a,b:"; }

cin>>a>>b;

obj1.setValue(a); Output:
obj2.setValue(b); Enter the value of Complex
Numbers a,b: 10 5
Input Values:
result = obj1+obj2; 10
cout<<"Input Values:\n"; 5
obj1.display(); Result:15

obj2.display();

Dalcomp Technologies 190


Another Example Of Binary Operator Overloading
class complex
{
int a,b;
public:
void getvalue()
{
cout<<"Enter the value of Complex Numbers a,b:";
cin>>a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a=a+ob.a;
t.b=b+ob.b;
return(t);
}

Dalcomp Technologies 191


complex operator-(complex ob)

{
complex t;
t.a=a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};

Dalcomp Technologies 192


void main() cout<<"Result:";
{ result.display();
clrscr(); result1.display();
complex obj1,obj2,result,result1; getch();
}
obj1.getvalue();
obj2.getvalue();
Output: Enter the value of Complex
Numbers a, b
result = obj1+obj2; 4 5
result1=obj1-obj2; Enter the value of Complex
Numbers a, b
cout<<"Input Values:\n"; 2 2
obj1.display(); Input Values
obj2.display(); 4 + 5i
2 + 2i
Result
6 + 7i
2 + 3i

Dalcomp Technologies 193


Example Of Unary Operator Overloading
class complex
{ void operator++()
{
int a,b; a=++a;
public: b=++b;
complex(){} }
void getvalue() void operator---()
{ {
a=--a;
cout<<"Enter the Two Numbers:"; b=--b;
cin>>a>>b; }
}

Dalcomp Technologies 194


void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr(); Output:
complex obj; Enter the two numbers: 3
6
obj.getvalue(); Increment Complex Number
++obj; 4+ 7i
cout<<"Increment Complex Number\n"; Decrement Complex Number
3+ 6i
obj.display();
--obj;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
} Dalcomp Technologies 195
Example Of Operator Overloading using
Friend Function
s operator+(int a, s s1)
#include <iostream>
{ s k;
#include <conio.h> k.i = a+s1.i;
class s k.j = a+s1.j;
{ return k;;
public: }
int i,j;
s()
{ i=j=0;}
void disp(){cout << i <<" " << j;}
void getdata(){cin>>i>>j;}
friend s operator+(int,s);
};

Dalcomp Technologies 196


int main()
{ s s2;
s2.getdata();
s s3 = 10+s2;
s3.disp();
getch();
return 0;
}

OUTPUT:

i=7 j=8

Dalcomp Technologies 197


Type Conversions
 It is the process of converting 1 type into another. It is also known as type
casting. There are two ways of achieving type conversion.

1. Implicit Type Conversion :- It is also called automatic type conversion. It


doesn’t require any conversion operator the value is automatically
converted into the type of left hand variable.

For Ex. Float a = 2.3;

int b = a; then b = 2;

2. Explicit Type Conversion :- This conversion is explicitly done using type cast
operator.

For Ex. Int a = 2; float b = (float) a; then b = 2.0;

int total , n; float avg; avg = (float) total/n;

Dalcomp Technologies 198


Example Of Data Conversions
class invent 1 //source class
{
int code; //item code
int items; //no. of items
float price; // cost of each item
public: invent 1(int a,int b,float c)
{
code = a;
items = b;
price = c;
}
void putdata()
{
cout<<“Code:”<<code<<“\n”;
cout<<“Items:<<items<<“\n”;
cout<<“Value:”<<price<<“\n”;
Dalcomp Technologies} 199
int getcode(){return code;}
int getitems(){return items;}
float getprice(){return price;}
operator float(){return(items* price);}
/* operator invent2() //invent 1 to invent 2
{
invent2 temp;
temp.code = code;
temp.value = price * items;
return temp;
}*/
}; //End of source class
class invent2 //destination class
{
int code;
float value;

Dalcomp Technologies 200


public:
invent 2()
{
code = 0; value =0;
}
invent 2(int x,float y) //constructor for initialization
{
code = x;
value = y;
}
void putdata ()
{
cout<<“Code: ”<<code<<“\n”;
cout<<“Value: ”<<value <<“\n\n”;
}
invent 2 (invent 1 p ) // constructor for conversion
{
code = p.getcode();
value = p.getitems() * p.getprice();
}
}; // End of destination class

Dalcomp Technologies 201


int main()
{
invent 1 s1(100,5,140.0);
invent 2 d1;
float total_value;
/* invent 1 to float */
total_value = s1;
/* invent 1 to invent 2*/
d1 = s1;

cout<<“Product details – invent 1 type”<<“\n”;


s1.putdata();

cout<<“\nStock Value”<<“\n”;
cout<<“Value = ”<<total_value<<“\n\n”;
cout<<“Product Details – invent 2type”<<“\n”;
d1.putdata();
return 0;
}

Dalcomp Technologies 202


End Of Chapter 8.
Any Question?

Home
Dalcomp Technologies 203
Chapter 9
Introduction To C++ I/O System
 Introduction To Streams
 Iostream Library Header Files
 Stream Input/Output Classes and Objects(I)
 Stream Input/Output Classes and Objects (II)
 Stream Output
 Stream-Insertion Operator
 Stream-Insertion/Extraction Operators
 Stream Input

Dalcomp Technologies 204


Introduction To Streams
Stream
A transfer of information in the form of a sequence of bytes

I/O Operations:
Input: A stream that flows from an input device ( i.e.:
keyboard, disk drive, network connection) to main memory
Output: A stream that flows from main memory to an
output device ( i.e.: screen, printer, disk drive, network
connection)

Dalcomp Technologies 205


Introduction To Streams
I/O operations are a bottleneck
o The time for a stream to flow is many times larger than the time it takes
the CPU to process the data in the stream

Low-level I/O
o Unformatted
o Individual byte unit of interest
o High speed, high volume, but inconvenient for people
High-level I/O
o Formatted
o Bytes grouped into meaningful units: integers, characters, etc.
o Good for all I/O except high-volume file processing

Dalcomp Technologies 206


Iostream Library Header Files

iostream library:
o <iostream.h>: Contains cin, cout, cerr, and clog objects

o <iomanip.h>: Contains parameterized stream manipulators

o <fstream.h>: Contains information important to user-


controlled file processing operations

Dalcomp Technologies 207


Stream Input/Output Classes and
Objects(I)
ios:
o istream and ostream inherit from ios
• iostream inherits from istream and ostream.
<< (left-shift operator)
o Overloaded as stream insertion operator

>> (right-shift operator)


o Overloaded as stream extraction operator
o Both operators used with cin, cout, cerr, clog, and with user-defined
stream objects

Dalcomp Technologies 208


Stream Input/Output Classes and Objects (II)
istream: input streams
cin >> someVariable;
• cin knows what type of data is to be assigned to someVariable
(based on the type of someVariable).
ostream: output streams
o cout << someVariable;
• cout knows the type of data to output
o cerr << someString;
• Unbuffered - prints someString immediately.
o clog << someString;
• Buffered - prints someString as soon as output buffer is full or
flushed

Dalcomp Technologies 209


Stream Output

ostream: performs formatted and unformatted output

o Uses put for characters and write for unformatted characters

o Output of numbers in decimal, octal and hexadecimal

o Varying precision for floating points

o Formatted text outputs

Dalcomp Technologies 210


Stream-Insertion Operator
<< is overloaded to output built-in types
o Can also be used to output user-defined types

o cout << ‘\n’;


• Prints newline character

o cout << endl;


• endl is a stream manipulator that issues a newline character and
flushes the output buffer

o cout << flush;


• flush flushes the output buffer

Dalcomp Technologies 211


Stream-Insertion/Extraction Operators
<< : Associates from left to right, and returns a
reference to its left-operand object (i.e. cout).
o This enables cascading
cout << "How" << " are" << " you?";

Make sure to use parenthesis:

cout << "1 + 2 = " << (1 + 2);


NOT
cout << "1 + 2 = " << 1 + 2;

Dalcomp Technologies 212


Character Output with Member Function put;
Cascading puts
put member function
o Outputs one character to specified stream
cout.put( 'A');
o Returns a reference to the object that called it, so may be
cascaded
cout.put( 'A' ).put( '\n' );
o May be called with an ASCII-valued expression
cout.put( 65 );
• Outputs A

Dalcomp Technologies 214


Stream Input
>> (stream-extraction)
o Used to perform stream input

o Normally ignores whitespaces (spaces, tabs, newlines)

o Returns zero (false) when EOF is encountered, otherwise returns


reference to the object from which it was invoked (i.e. cin)

• This enables cascaded input

cin >> x >> y;

>> controls the state bits of the stream


o failbit set if wrong type of data input

o badbit set if the operation fails


Dalcomp Technologies 215
End Of Chapter 9.
Any Question?

Home
Dalcomp Technologies 216
Chapter 10
Exception Handling
 Introduction To Exceptions

 Introduction To Throw

 Catch(){}

 Some Points To Remember

Dalcomp Technologies 217


Introduction To Exceptions
 Exceptions provide a way to handle the errors generated by our
programs by transferring control to functions called handlers.

 To catch exceptions we have to place our code on which we


want exception handling in the try block. If an exception occurs
the control is passed to the handler, otherwise the handlers are
ignored.

 The code to be executed, that may produce exceptions, is


placed in the try block and the error handlers are declared with
the keyword catch.
Dalcomp Technologies 218
Program Of Exceptions
 First Program:-

#include <iostream>
using namespace std;
int main ()
{
try
{
throw 10;
}
catch (int e)
{
cout << “We have a problem!!” << endl;
}
return 0;
Output
} : We have a problem!!!

Dalcomp Technologies 219


Introduction To Throw
 The throw expression accepts one parameter as its argument and this is
passed to the exception handler. You can have a number of throw
statements at different parts of your try block with different values being
thrown so that the exception handler on receiving the parameter will know
what restorative actions to take.
try
{ // code
if ( x )
throw 10;
// code
if (y)
throw 20;
//code
}

Dalcomp Technologies 220


Catch(){}
 The exception handler can be identified by the keyword catch . catch always
takes only one parameter. The type of the catch parameter is important as
the type of the argument passed by the throw expression is checked against it
and the catch function with the correct parameter type is executed. This way
we can chain multiple exception handlers and only the one with the correct
parameter type gets executed.
try { // code here }
catch (int param) {
cout << "int exception";
}
catch (char param) {
cout << "char exception";
}
catch (...) {
cout << "default exception";
}

 The catch(…) handler catches all exceptions, no matter what type. It can be
used as a default handler if declared last.

Dalcomp Technologies 221


Example Of Exception Handling
(Divide By Zero)
#include<iostream.h> try
#include<conio.h> {
void main() if((a-b)!=0)
{ {
int a,b,c; d=c/(a-b);
float d; cout<<"Result is:"<<d;
clrscr(); }
cout<<"Enter the value of a:"; else
{
cin>>a;
throw(a-b);
cout<<"Enter the value of b:";
}
cin>>b;
cout<<"Enter the value of c:";
cin>>c;
}
Dalcomp Technologies 222
catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}

getch();
}
Output:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40

Answer is infinite because a-b is: 0

Dalcomp Technologies 223


Example Of Exception Handling(Multiple
#include<iostream.h>
Catch)
#include<conio.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}

catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x;
}

Dalcomp Technologies 224


catch(char x)
{
cout<<"Catch a character and that character
is:"<<x;
} Output:
} Testing multiple catches
Catch a integer and that integer is: 10
void main()
Catch a character and that character is: x
{
clrscr();
cout<<"Testing multiple catches\n:";
test(10);
test(0);
getch();
}

Dalcomp Technologies 225


Some Points To Remember

 You can nest the try-catch blocks.

 After exception handling the program returns to the point after

the try-catch block, not after the throw statement.

Dalcomp Technologies 226


End Of Chapter 10.
Any Question?

Home
Dalcomp Technologies 227
Chapter 11.
Templates
 Introduction To Templates

 Advantages & Disadvantages Of Templates

 Types Of Templates

 Function Template With Example

 Class Template With Example

 Points To Remember
Dalcomp Technologies 228
Introduction To Templates

 A template is a C++ feature that allows functions and classes to


be defined with any type.

 With a non-templated function, the parameters to that function


are declared to be of a particular type. By defining a template
function, that function can be called with a compatible type and
the compiler will use the type derived from the parameter.

Dalcomp Technologies 229


Advantages & Disadvantages Of Templates
 Advantages :-

 Template classes and functions allow us to use different data

types with a single definition.

 Template classes and functions reduce the source code by

avoiding a duplicated code for different data types.

Dalcomp Technologies 230


 Templates are the building blocks of generic programming.

 Templates are typesafe because the data type of the template on

which it operates is known at compile time.

Dalcomp Technologies 231


Advantages & Disadvantages Of Templates
 Disadvantages :-

 Some compilers support templates poorly. So, the use of templates could

decrease code portability.

 A compiler generates an additional code for each data type which results in

larger executables.

 It is difficult to debug the code developed using templates. Since the

compiler replaces the templates, it becomes difficult for the debugger to

locate the code at runtime.

Dalcomp Technologies 232


 As C++ does not have binary runtime extensibility, templates cannot

be linked and distributed as library.

 Templates of templates (nested templates) are not supported by all

compilers.

 The use of templates makes the code less portable as all features are

not supported by all compilers.

 The use of templates in a program increases compilation time.

Dalcomp Technologies 233


Types Of Template

There are two types of Template:

1. Function Template
2. Class Template

Dalcomp Technologies 234


Function Template

 Function templates are special functions that can operate with

generic types. This allows us to create a function template

whose functionality can be adapted to more than one type or

class without repeating the entire code for each type.

Dalcomp Technologies 235


 In C++ this can be achieved using template parameters. A

template parameter is a special kind of parameter that can be

used to pass a type as argument: just like regular function

parameters can be used to pass values to a function, template

parameters allow to pass also types to a function. These

function templates can use these parameters as if they were any

other regular type.

Dalcomp Technologies 236


Example Of Function Template
The format for declaring function templates with type

parameters is:

template <class identifier> function_declaration;

template <typename identifier> function_declaration;

Dalcomp Technologies 237


// function template
template <class T>
T GetMax (T a, T b) {
return (a>b?a:b);
}

int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m); 6
cout << k << endl; 10
cout << n << endl;
return 0;
}

Dalcomp Technologies 238


Another Example Of Function Template
template<class t>
void swap(t &x,t &y)
{
t temp=x;
x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"\n a and b before swaping :"<<a<<"\t"<<b;
swap(a,b);
cout<<"\n a and b after swaping :"<<a<<"\t"<<b;
cout<<"\n\n c and d before swaping :"<<c<<"\t"<<d;
swap(c,d);
cout<<"\n c and d after swaping :"<<c<<"\t"<<d;
}
Dalcomp Technologies 239
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter A,B values(integer):";
cin>>a>>b;
cout<<"Enter C,D values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}

Dalcomp Technologies 240


Output:
Enter A, B values (integer): 10 20
Enter C, D values (float): 2.50 10.80

A and B before swapping: 10 20


A and B after swapping: 20 10

C and D before swapping: 2.50 10.80


C and D after swapping: 10.80 2.50

Dalcomp Technologies 241


Class Template
 We also have the possibility to write class templates, so that a class
can have members that use template parameters as types.
 You can declare an object of a class template.

 For example:
template <class T>
class mypair
{
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};

Dalcomp Technologies 242


Example Of Class Templates
#include <iostream>

template <class T>


class mypair
{
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T> :: getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
Dalcomp Technologies 243
int main ()
{
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}

OUTPUT: 100

Dalcomp Technologies 244


Points to Remember

 Template implements the concept of generic programming.

 Template classes and functions allow use of different data types


with a single definition.

 Template classes and functions reduce code by avoiding


duplicate code for different data types.

 It is possible to use multiple generic types in a single class or


function template.

Dalcomp Technologies 245


Points to Remember
 We can explicitly overload the template.

 It is possible to use non-type template argument in template.

 A class generated from a class template is called a generated


class.

 A function generated from a function template is called a


generated function.

 A static data member generated from a static data member


template is called a generated static data member.

Dalcomp Technologies 246


End Of Chapter 11.
Any Question?

Home
Dalcomp Technologies 247
Chapter No.12
File Handling
 Using Input/Output Files
 General File I/O Steps
 Streams
 Predefined console streams
 Why to use Files?
 Classes for Stream I/O in C++
 File Modes
 File pointers
 Dealing with Binary files
 Binary File I/O Examples

Dalcomp Technologies 248


Using Input/Output Files

 Files in C++ are interpreted as a sequence of bytes stored on some storage

media.

 The data of a file is stored in either readable form or in binary code called as

text file or binary file.

 The flow of data from any source to a sink is called as a stream


Using Input/Output Files
 Computer programs are associated to work with files as it helps
in storing data & information permanently.

 In C++ this is achieved through a component header file called


fstream.h

 The I/O library manages two aspects- as interface and for


transfer of data.

 The library predefine a set of operations for all file related


handling through certain classes.

Dalcomp Technologies 250


Using Input/Output Files

A computer file

o is stored on a secondary storage device (e.g., disk);

o is permanent;

o can be used to provide input data to a program or receive


output data from a program, or both;

o must be opened before it is used.


General File I/O Steps

 Declare a file name variable

 Associate the file name variable with the disk file name

 Open the file

 Use the file

 Close the file


Using Input/Output Files

stream - a sequence of characters


interactive (iostream)
 cin - input stream associated with keyboard.
 cout - output stream associated with display.
file (fstream)
 ifstream - defines new input stream (normally associated with a file).
 ofstream - defines new output stream (normally associated with a file).
• Stream of bytes to do input and output to different devices.
• Stream is the basic concepts which can be attached to files, strings, console and
other devices.
• User can also create their own stream to cater specific device or user defined
class.
Streams
 A stream is a series of bytes, which act either as a source from which data
can be extracted or as a destination to which the output can be sent. Streams
resemble the producer and consumer model

 The producer produces the items to be consumed by the consumer. The


producer and the consumers are connected by the C++ operators >> or <<.
For instance , the keyboard exhibits the nature of only a producer,printer or
monitor screen exhibit the nature of only a consumer. Whereas , a file
stored on the disk , can behave as a producer or consumer, depending upon
the operation initiated on it.
Predefined console streams

C++ contains several predefined streams that are opened automatically

when the execution of a program starts.

1) cin :standard input (usually keyboard) corresponding to stdio in C

2) cout :standard output (usually screen) corresponding to stdout in C

3) cerr :standard error output (usually screen) corresponding to stderr in C

4) clog : A fully buffered version of cerr (No C equivalent)


Why to use Files?
 Convenient way to deal large quantities of data.
 Store data permanently (until file is deleted).
 Avoid typing data into program multiple times.
 Share data between programs.
 We need to know:
o how to "connect" file to program
o how to tell the program to read data
o how to tell the program to write data
o error checking and handling EOF
Classes for Stream I/O in C++
When working with files in C++, the
following classes can be used:
ofstream – writing to a file
ifstream – reading for a file
fstream – reading / writing

When ever we include <iostream.h>, an


ostream object, is automatically defined –
ios is the base class. this object is cout.
istream and ostream inherit from ios ofstream inherits from the class ostream
ifstream inherits from istream (and (standard output class).
ios) ostream overloaded the operator >> for
ofstream inherits from ostream (and standard output.…thus an ofstream object
ios) can use methods and operators defined in
iostream inherits from istream and ostream.
ostream (& ios)
fstream inherits from ifstream,
iostream, and ofstream
File Modes
Name Description
ios::in Open file to read
ios::out Open file to write
ios::app All the date you write, is put at the end of the file.
It calls ios::out
ios::ate All the date you write, is put at the end of the file.
It does not call ios::out
ios::trunc Deletes all previous content in the file. (empties
the file)
ios::nocreate If the file does not exist, opening it with the open()
function gets impossible.
ios::noreplace If the file exists, trying to open it with the open()
function, returns an error.
ios::binary Opens the file in binary mode.
File pointers
 Each file has two associated pointers known as the file pointers.
One of them is called the input pointer or get pointer.

 The get pointer specifies a location from which the current reading
operation is initiated
Other is called the output pointer or put pointer.

 The put pointer specifies a location from where the current writing
operation is initiated
We can use these pointers to move through the files while reading or
writing.

 The input pointer is used for reading the contents of a given file location and
the output pointer is used for writing to a given file location.
Functions for manipulation of file pointers
seekg() Moves get pointer (input) to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Gives the current position of the get pointer.
tellp() Gives the current position of the put pointer.
File Open Mode

#include <fstream>
int main(void)
{
ofstream outFile("file1.txt", ios::out);
outFile << "That's new!\n";
outFile.close();
Return 0;
}

If you want to set more than one open mode, just use the OR
operator- |. This way:

ios::ate | ios::binary
Dealing with Binary files
• Functions for binary file handling
get(): read a byte and point to the next byte to read
put(): write a byte and point to the next location for write
read(): block reading
write(): block writing

flush():Save data from the buffer to the output file.


Binary File I/O Examples
//Example 1: Using get() and put()
#include <iostream>
#include <fstream>
void main()
{
fstream File("test_file",ios::out | ios::in | ios::binary);
char ch;
ch='o';
File.put(ch); //put the content of ch to the file
File.seekg(ios::beg); //go to the beginning of the file
File.get(ch); //read one character
cout << ch << endl; //display it
File.close();
}
File I/O Example: Writing

#include <fstream>
using namespace std;
int main(void)
{
ofstream outFile(“fout.txt");
outFile << "Hello World!";
outFile.close();
return 0;
}
File I/O Example: Reading
#include <iostream>
#include <fstream>

int main(void)
{
ifstream openFile(“data.txt"); //open a text file data.txt
char ch;
while(!OpenFile.eof())
{
OpenFile.get(ch);
cout << ch;
}
OpenFile.close();

return 0;
}
File I/O Example: Reading
#include <iostream>
#include <fstream>
#include <string>

int main(void)
{
ifstream openFile(“data.txt"); //open a text file data.txt
string line;

if(openFile.is_open()){ //
while(!openFile.eof()){
getline(openFile,line);//read a line from data.txt and put it in a string
cout << line;
}
else{
cout<<“File does not exist!”<<endl;
exit(1);}
}
openFile.close();
return 0;
}
To access file handling routines:
#include <fstream.h>
1: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
2: To connect your program's variable (its internal name) to an
external file (i.e., on the Unix file system):
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
3: To see if the file opened successfully:
if (in_stream.fail())
{ cout << "Input file open failed\n";
exit(1); // requires <stdlib.h>}
To get data from a file (one option), must declare a variable to
hold the data and then read it using the extraction operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
4: To put data into a file, use insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and written in order
– generally can't back up.
5: When done with the file:
in_stream.close();
out_stream.close();
Reading /Writing from/to Binary Files
 To write n bytes:
 write (const unsigned char* buffer, int n);
 To read n bytes (to a pre-allocated buffer):
 read (unsighed char* buffer, int num)
#include <fstream.h>
main()
{
int array[] = {10,23,3,7,9,11,253};
ofstream OutBinaryFile("my_b_file.txt“, ios::out | ios::binary);
OutBinaryFile.write((char*) array, sizeof(array));
OutBinaryFile.close();
}
C++ has some low-level facilities for character I/O.
char next1, next2, next3;
cin.get(next1);
Gets the next character from the keyboard. Does not skip over
blanks or newline (\n). Can check for newline (next == '\n')
Example:
o cin.get(next1);
o cin.get(next2);
o cin.get(next3);
Predefined character functions must #include <ctype.h> and can
be used to
• convert between upper and lower case
• test whether in upper or lower case
• test whether alphabetic character or digit
• test for space
Reading /Writing from/to Textual Files

#include <fstream.h>
To write: main()
{
put() – writing single character // Writing to file
<< operator – writing an object ofstream OutFile("my_file.txt");
OutFile<<"Hello "<<5<<endl;
To read: OutFile.close();
get() – reading a single character
int number;
of a buffer char dummy[15];
getline() – reading a single line
>> operator – reading a object // Reading from file
ifstream InFile("my_file.txt");
InFile>>dummy>>number;

InFile.seekg(0);

InFile.getline(dummy,sizeof(dummy));
InFile.close();
}
Binary file operations
In connection with a binary file, the file mode must
contain the ios::binary mode along with other mode(s)

To read & write a or on to a binary file,


as the case may be blocks of data are accessed
through
the use of C++ read() and write() respectively.
Handling binary data

#include <fstream>
using namespace std;

int main(){

ifstream in(“binfile.dat”);
ofstream out(“out.dat”);
if(!in || !out) { // return}
unsigned int buf[1024];
while(!in){
in.read(buf, sizeof(unsigned
int)*1024);
out.write(buf, sizeof(unsigned
int)*1024);
}
End Of Chapter 12.
Any Question?

Home
Dalcomp Technologies 276
Thank You

Dalcomp Technologies
Home 280

You might also like