You are on page 1of 200

Typical Structure of POP Programs

Main Program

Function - 1

Function - 2

Function - 4

Function - 6

Function - 7

Function - 3

Function - 5

Function - 8

Relationship of data and functions


in POP
Global Data

Global Data

Function - 1

Function - 2

Function - 3

Local Data

Local Data

Local Data

Procedural Oriented Programming


Emphasis is on doing things.
Large programs are divided into smaller
programs known as functions.
Most of the functions share global data.
Data move openly around the system from
function to function.
Functions transform data from one form to
another.
Employs top-down approach.

Disadvantages of POP
Global data are more vulnerable to changes by
a function. In large program it gets very difficult
to identify what data is used by what functions.
Incase we need changes in an external data
structure, we need to revise all functions that
access that data structure.
Complexity increases.
It does not model real world problems very well.

Organization of data and functions


in OOP
Data

Data

Functions

Functions

Data

Functions

Object Oriented Programming


Emphasis is on data rather than on procedure.
Programs are divided into what are known as objects.
Data structures are designed such that they
characterize the objects.
Functions and data are tied together.
Data is hidden and cannot be accessed by external
functions.
Objects communicate with each other through
functions.
Changes and additions can be easily achieved.
Follows bottom-up approach.

Object Oriented Programming


Basic Concepts
Objects
Classes
Data abstraction and data encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message passing

Object Oriented Programming


Classes
User defined data type designed to solve
a particular problem.
Collection of objects
It contains set of data and functions which
manipulate over the data.

Object Oriented Programming


Objects
Objects are basic runtime entities.
They are variables of type class.
They are declared as
class-name var-name.
If fruit is a class and mango is an object
then the syntax is : fruit mango.

Object Oriented Programming


Data Encapsulation
The wrapping up of data and functions in
the same unit .
Data is not accessible to the outside
world.
This insulation of data is called data
hiding.

Object Oriented Programming


Data Abstraction
Act of representing essential features
without including background features.
Classes use the concept of data
abstraction so they are also called
abstract data types (ADT).

Object Oriented Programming


Inheritance
Process by which objects of one class
acquire the properties of another class.
Main advantage is reusability.

Object Oriented Programming


Polymorphism
Greek word which means ability to take
many forms.
Using plus sign with numbers gives sum
where as with two strings yields
concatenated string.

Object Oriented Programming


Two categories of languages :

Object Based Languages


- Data encapsulation
- Data hiding and access mechanism
-Operator overloading
e.g.:- Visual Basic , Ada.

Object based Languages


- Object Based features +
- Inheritance
- Dynamic Binding.
e.g.:- C++, Java, Smalltalk , Object Pascal.

Insertion Operators
Insertion operator or put to operator <<
inserts the contents of the variable on its
right to the object on its left.
int a = 5;
cout<< a;
Since it inserts on the output screen it is
called the insertion operator.

Extraction Operator
The extraction operator or the get from
operator >> extracts the value from the
keyboard and assigns it to the variable on
the right.
int a;
cin >> a;
Since it extracts data from the user it is
called the extraction operator.

Structure of C++ Program

Include Files
Class Declaration
Member function definitions
Main function program

Identifiers
They are names of names of variables, arrays ,
functions and classes.
Naming identifiers
- alphabets, digits and underscore are
permitted
- Cannot start with digit
- Upper case and lower case are distinct.
- Keyword cannot be used.
- no limit to the length , while it is 32 in C.

C++ Data Types


C++ Data Types

User Defined type


Structure
Union, Class
Enumeration
Integer type
Int
char

Built in type

Void

Derived type
Array, Pointer
Reference
Function
Floating type
Float
Double

Keywords
Fixed words having fixed meanings
Example : int , float , etc.

Enumerated Data Type


User defined type that provides a way of
attaching names with numbers.
Example : enum shape { circle , square ,
triangle };
shape is a new data type now.
variables of this type can be created
now.
Circle is assigned the value 0 by default ,
square 1 and so on.

Enumerated Data Type


Enum colour { red , blue = 9 , green
,yellow};
Here red = 0 , blue = 9 , green = 10 and
yellow = 11.
Color background = blue; // allowed
Color background = 7; //error
Color background = (colour) 7;

Pointers
Pointers are variables
that store addresses of
other variables as values.
int a = 10;
int *ptr;
ptr= &a;
Here 2 bytes
is allocated for ptr and 2
bytes for a. In ptr &a is
stored whereas in
address of a 10 is stored.

ptr holds &a

a = 10

Reference Variables
A reference variable
provides an alias or
an alternative name
for an already existing
variable.
float total = 100;
float &sum = total;

total / sum

Operators
Types of Operators

Unary Operators
One operand
e.g. -a

Binary Operators
Two operands
e.g. a+b

Ternary Operators
3 operands
e.g. (a>b)?a:b;

Precedence and Associativity


Precedence is the priority level of
operators.
When we have more than one operators
of the same precedence , associativity is
considered,

Casting
Casting conversion
of one type to
another.
Implicit Casting
Automatic casting
float f = 19.5;
int I = f;

Explicit Casting
Manual casting
float f = 19.5;
int I = (int)f;

Decision Making and Branching


Simple If Statement
If( condition is true)
{
instruction -1;
instruction -2;
..
}
instruction -3;

Accessing Global Variable


int i = 10;
void main()
{
int i =20;
{
int i = 30;
cout<<i;
cout<<::i;
}
cout<<i;
cout<<::i;
}

Output :
30 10 20 10.
:: operator prints the global
variable.

new and delete operators


new operator
Used to allocate memory space
dynamically.
Syntax :
int *p = new int;
int *p = new int(5); assigns value 5
int *p = new int[5]; creates 5 variables.

delete operator
delete operator
Used to release memory space
dynamically.
E.g.: delete p;
int *p = new int[5];
delete [] p;
The brackets denote that p was pointing to
an array.

Decision Making and Branching


Simple If Statement
If( condition is true)
{
instruction -1;
instruction -2;
..
}
instruction -3;

Decision Making and Branching


If Else Statement
If( condition is true)
{
instruction -1;
instruction -2;
..
}
else
{
instruction -3;
..
}
instruction -4;

Decision Making and Branching


Else if ladder
If( condition)
{ ..
} else if (condition)
{ ..
} else if( condition)
{ ..
}else{
..
}

Decision Making and Branching


Nested if else
If( condition)
{ ..
if( condition) { .. }
else { .. }
} else if (condition)
{ ..
}

Decision Making and Branching


Switch Statement
switch (expression)
{
case 1:
instruction-1;
break;
case 2:
instruction-2;
break;
default:
instruction-2;
break;
}

Decision Making and Looping


3 steps of looping.
Initialization- assigning an initial value to
the control variable
Condition checking checking the
condition and then executing the
instructions in the body of the loop.
Incrementation or decrementation.

Decision Making and Looping


While loop
Print 1 to 10 numbers using while loop
int I = 0;
// initialization
while (I <=10) // condition checking
{
cout<<I;
i++;
//incrementation
}

Decision Making and Looping


for loop
Print 1 to 10 numbers using while loop
for(i=0;i <=10;i++)
{
cout<<I;
}
All the three steps are included in the
brackets of for loop.

Decision Making and Looping


Do While loop
Print 1 to 10 numbers using do while loop
int I = 0;
// initialization
do
// condition checking
{
cout<<I;
i++;
//incrementation
} while (I <=10) ;

Decision Making and Looping


Loops
Entry controlled
Loops
e.g. for loop,while loop

Exit controlled
Loops
e.g. do while loop

Condition checking
Condition checking
n+1 times
n times
Body execution n times Body execution n times

Functions
Subprograms
Set of finite instructions written down to
accomplish a specific task.
Reduces complexity.
Up gradation becomes comparatively
easy.
Debugging becomes easy.

Functions
Three parts
Declaration
return-type func-name( type of arg);
int add( int , int);
Definition
int add( int a, int b)
{
return (a+b);
}
Calling
sum = add (x,y);

Difference between call by pointers


and call by references
Call by pointers
void swap (int * , int *);
void swap (int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
swap (&a,&b); //calling

Call by references
void swap (int & , int &);
void swap (int &ra, int &rb)
{
int temp;
temp = ra;
ra = rb;
rb = temp;
}
swap (a,b); //calling

Default Arguments
float s_interest(int p,int y,int rate = 2);
float s_interest(int p,int y,int rate )
{
int interest = p*rate*y/100;
return interest
}
s_interest(1000,5);
//calling
s_interest(1000,5,4);
//calling

Classes
Class specification has two parts Class declaration
describes the type and scope of its
members
Class function definition.
describe how the functions are
implemented.

Classes
class class-name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

Data hiding in classes


Private area
No
Access
From outside

Data
Functions

Public area
Access
From outside
allowed

Data
Functions

Classes
Class item
{
private:
int number;
int cost;
public :
void getdata( int c,int no)
//definition
{
cost = c;
number = no;
}
void putdata( )
//definition
{
cout<< number : <<number <<\n cost : <<cost;
}
};

Creating Objects
Objects are variables of type class.
So the syntax is
class-name object-name;
Objects can call all the members
functions.
Syntax :
Object.function-name();

Creating objects
void main()
{
item earPhones;
earPhones.getdata(10,1000);
//
function call
earPhones.putdata(); // function call
}

Memory Allocation
When a class is defined memory is allocated
partially.
Memory for functions is allocated once when
the class is defined.
Sum of memory space of all data members is
allocated when an object is created.
Every object has a separate set of data
members.

Memory allocation for objects


class car
{
int cost, avg;
float speed;
public:
..functions..
};
void main()
{
test city, accord;
}

Here 16 bytes of data is


allocated .
8 bytes for object city and 8
bytes for object accord.
city

cost
avg
speed

accord

cost
avg
speed
functions

Static Variables
Data members of a class that are created
just once.
The same copy is accessed by all the
objects of that class.
Since they are created at the class level
they are also called class variables.
They are initialized to 0.

Static Data Members


Static data
Members

Object-1

Object-2

Object-n

Static Data Members


class test
{
int I;
static int x;
};
int test :: x;

//declaration
//definition

Static Member Functions


Members which are declared as
static have the following
properties

Can access only static


members variables.

Can be called using the class


name.

class test
{
int x,y,z;
static int count;
public:
static void func()
{
count++;
x++; //error
}
};
Void main()
{ test func(); // call
}

Arrays of Objects
class test
{
int x,y,z;
static int count;
public:
functions..
};
Void main()
{
test t[3];
}

count

t[0]

x,y,z

t[1]

x,y,z

t[2]

x,y,z

Constructors
Special member function whose task is to
initialize the objects of its class.
They have the same name as the class
name.
They are called automatically when
objects are created.

Constructors
There are three types Default constructor
- does not have arguments.
-is called automatically
Parameterized constructor
Copy constructor

Default Constructors
Default constructor
- does not have arguments.
- is called automatically when an object is created.
class xyz
{
int a;
public:
xyz();
};
void xyz :: xyz()
{
a = 0;
void main()
{
xyz obj1;
}

Parameterized Constructors
Parameterized constructor
- takes arguments.
- is called automatically when
an object is created.
class xyz
{
int a;
public:
xyz();
xyz(int);
};
void xyz :: xyz()
{
a = 0;
}

void xyz :: xyz(int x)


{
a = x;
}
void main()
{
xyz obj1(5); //implicit
call to
parameterized
constructor
xyz obj2 = xyz(10);
//explicit call
}

Copy Constructor
Copy constructor
- used to copy an object to
another
- takes reference of its type as
an argument
class xyz
{
int a;
public:
xyz();
xyz(int);
xyz(xyz &); // declaration
};
void xyz :: xyz() { a = 0;}

void xyz :: xyz(xyz &temp)


{
a = temp.a;
}
void main()
{
xyz obj1
xyz obj2(obj1);
xyz obj3 = xyz(obj1);
//explicit call
}

Points to note about constructors

Should be declared in the public section


Invoked automatically when objects are created
Don't have return types not even void.
Cannot be inherited.
They can have default arguments.
Cannot be virtual.
Objects with constructors cannot be used as
members of unions.
Make implicit calls to new and delete.

Destructors
Member function whose name is same as
the class name.
Used to destroy the objects
Cannot return any value not even void.
Cannot take arguments.
Preceded by a tilde~ sign.

Destructors
class alpha
{ public:
alpha(){
count++;
cout<<count;
~alpha(){
cout<<count;
count--;
}
};

int main()
{
alpha A1,A2,A3,A4;
{ alpha A5; }
{alpha A6; }
}
Output:
1234
55
55
4321

Destructors
When any object gets out of scope the
destructor is implicitly called.
Objects are destroyed in the opposite
order of their creation.

Inheritance
Inheritance
Process by which objects of one class
acquire the properties of another class.
Main advantage is reusability.

Types of Inheritance
Types Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance

Types of Inheritance
Class 1

Class 2
Simple Inheritance

Class 1

Class 2

Class 3

Class 4

Hierarchical inheritance

Types of Inheritance
Class 1

Class 2

Class 1

Class 2
Class 3
Class 3

Multiple Inheritance

Multilevel Inheritance

Types of Inheritance
Class 1

Class 2

Class 3

Class 4

Hybrid Inheritance

Single Inheritance
Suppose B is the base class.
We want to create a class D derived from
B.
Syntax for deriving it is :
class der-class-name : mode base-class-n
mode private , protected , public.

Single Inheritance - public


class B{
int a;
public :
int b;
};
class D : public B
{
int x;
public:
func();
};

private : a
public : b
Class B

private : x
public : b , func()

Class D

Single Inheritance
Protected data members
class B{
int a;
protected : int y;
public :
int b;
};
class D : public B
{
int x;
public:
func();
};

private : a
protected : y
public : b
Class B

private : x
protected : y
public : b , func()

Class D

Single Inheritance - private

class B{
int a;
public :
int b;
};
class D : private B
{
int x;
public:
func();
};

private : a
public : b
Class B

private : x,b
public : func()

Class D

Single Inheritance - protected


class B{
int a;
protected: int y;
public :
int b;
};
class D : protected B
{
int x;
public:
func();
};

private : a
protected : y
public : b
Class B

private : x
protected : b , y
public : func()

Class D

Inheritance
Base Class visibility

Mode of inheritance
Private

Protected

Public

Private

Not Inherited

Not Inherited

Not Inherited

Protected

Protected

Private

Protected

Public

Public

Private

Protected

Multiple Inheritance
class B1{..};
class B2{..};
class B3{..};
class D : private B1,
protected B2,
public B3
{ .. };
void main()
{ .. }

Resolving ambiguity
class B1{
public: display();
};
class B2{
public: display();
};
class D : public B1,public
B2
{ .. };

void main()
{
D obj;
obj.display(); // error
obj.B1::display();
obj.B2::display();
}

Hybrid Inheritance
class Parent
{ public :
calc();
};
class child1 : public
virtual Parent {..};
class child2 : virtual
public Parent{ .. };

class grandchild : public


child1,public child2
{}
void main()
{
grandchild gc;
gc.calc();
}

Inheritance with Default


Constructors
class base{
int a;
public:
base(){
cout<<Base Class!!}
}
class derived : public base{
int b;
public:
derived(){
cout<<derived Class!!}
}

void main()
{
derived d;
}
Output :
Base Class
derived Class
-Base class constructor is
called first and then
derived class constructor
is called.
-Default constructor is
implicitly called.

Inheritance with Parameterized


Constructors
class base{
int a;
public: base(){}
base(int aa){ a = aa;
cout<< a = <<a; }
}
class derived : public base{
int b;
public: derived(){}
derived( int aa, int bb) : base(aa)
{ b = bb ;
cout<< a = <<a; }
}

void main()
{
derived d(5,10);
}
Output :
a=5
b = 10
- Base class parameterized
constructor is called first and
then derived class constructor
is called.
-Parameterized constructor of the
base class has to be explicitly
called from the derived class
Parameterized constructor

Composition vs Inheritance
Having an object of a
class as a member of
another class is called
composition.
An object of wheel class
will be a member of the
car class.
we can say that car has a
wheel.
Composition exhibits hasa relationship.

Object of one class


obtaining the properties
of an object of another
class is called
inheritance.
Suppose car class
inherits from vehicle
class.
Then we can say that car
is a vehicle.
Inheritance exhibits is-a
relationship.

Composition Syntax
class X
{ int a;
public:
void ass(int aa)
{ a = aa ;}
void get()
{ return a ;}
};
Class Y
{ int a;
public:
X x;

void ass(int aa)


{ a = aa ;}
void get()
{ return a ;}
};
void main()
{
Y y;
y.ass(10);
y.x.ass(20);
y.get();
y.x.get();
}
Output : 10 20

Friend Functions
In cases when we want the non member
functions to access the private of a class
We declare those functions as friend.
Three types :
A global function declared friend of a class.
Member function of one class as friend of
another class.
A class as a friend of another.

A global function declared friend of


a class.
class sample
{ int a,b;
public:
void setvalue()
{ a = 25;b = 50; }
friend float mean(sample s);
};
float mean(sample s)
{
return((s.a + s.b)/2);
}

int main()
{
sample x;
x.setvalue();
cout<<mean value :
<<mean(x);
return 0;
}

A global function declared friend of


two classes
class ABC; // forward declaration
Class XYZ
{ int x;
public:
void setvalue(int i)
{ x = i;}
friend void max(XYZ,ABC);
};
void max(XYZ m,ABC n)
{
if(m.x > n.a ) cout<< n.a;
else cout<< m.x;
}

class ABC
{ int a;
public:
void setvalue(int i){ a = i;}
friend void max(XYZ,ABC);
};
int main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(10);
max(xyz,abc);
}

Member function of one class as


friend of another class.
class X
{
int fun1();
};
class Y
{
friend int X :: fun1();
..
};

A class as a friend of another.


class X
{
int fun1();
};
class Z
{
friend class X;
};
Here class Z can access the private of class X.
Vice versa is not true.

Things to note about friend


functions.
They are not in the scope of the class.
They cannot be called using an object.
Cannot access the member names
without the object.
Can be declared in the private or public
region without affecting its meaning.
Usually it has objects as arguments.

Inline Functions
Functions which are expanded in line when
they are invoked.
That is that compiler replaces the function
call with the corresponding function code.

Inline Functions
Two ways of declaring a
function as inline.
Define the function
inside the class.
class abc{
public :
void func(){ ..}
// inline function
};

With the keyword


inline
Class abc{
public:
void func();
};
inline void func()
{
}

Advantages and Disadvantages


Advantages
Speed increases. But as size increases
the advantages diminish.
Disadvantages
It takes up more memory space.

Inline Functions
Inline keyword is a mere request to the
compiler.
Situations where inline functions may not
work :
- if a loop , switch or goto is used.
- functions not returning values, if a
return statement exists.
- functions contain static.
- functions are recursive.

Polymorphism
Greek term meaning one thing taking
multiple forms.
Must know terms
- early binding/static linking
- late binding/dynamic linking

Polymorphism
Polymorphism

Compile time
polymorphism

Function
Overloading

Operator
Overloading

Run time
polymorphism

Virtual
Functions

Function Overloading
When more than one function has the
same name but different number and type
of arguments, it is called function
overloading.
Depending on the number of arguments
specified during function call the
respective function is executed.
The linking takes place at compile time so
it is called early binding or static linking.

Function Overloading
int vol(int r)
{
return (r*r*r);
}
int vol(int r,int h)
{
return(3.14*r*r*h);
}
int vol(int l,int b,int h)
{
return (l*b*h);
}

void main()
{
int cube , cylinder, cuboid;
cube = vol(5);
cylinder = vol(5,3);
cuboid = vol(6,7,4);
}
Here there are 3 functions
with the same name but
different number of
arguments.

Constructor Overloading
Here there are three functions
constructors with the same name
but different arguments. This is
called constructor overloading.
class xyz
{
int a;
public:
xyz();
xyz(int);
xyz(xyz &); // declaration
};
void xyz :: xyz() { a = 0;}

void xyz :: xyz(xyz &temp)


{
a = temp.a;
}
void main()
{
xyz obj1
xyz obj2(obj1);
xyz obj3 = xyz(obj1);
//explicit call
}

Operator Overloading
The mechanism of giving special meaning
to
an operator is called operator overloading.
We can almost create a new language of
our own by overloading operators.

Operator Overloading
The following are the operators that cannot
be overloaded.
Class member access operator . or *.
Scope resolution operator ::
Size operator (sizeof)
Conditional operator (?:)

Operator Overloading
Operator
overloading
Unary
operators

Member
function

No
argument

Friend
function

One
argument

Binary
operators

Member
function

One
argument

Friend
function

Two
argument

Overloading unary operators using


member functions
class space
{
int x,y,z;
public :
void get(int a,int b,int c)
{ x = a; y = b; z = c;}
void display(){..}
void operator-();
};
void space :: opertor-()
{ x = -x; y = -y; z = -z;}

void main()
{
space s;
s.get(3,-6,9);
s.display();
-s;
s.display();
}
Output:
X = 3, y = -6; z = 9
X = -3, y = 6; z = -9

Overloading unary operators using


member functions
Since this function is the member of the
class the data members can be accessed
directly .
A statement like
s2 = -s1; would not work because
the function does not return any value.
If modified to return an object it can
work.

Overloading unary operators using


friend functions
class space
{
int x,y,z;
public :
void get(int a,int b,int c)
{ x = a; y = b; z = c;}
void display(){..}
friend void operator-(space&);
};
void operator-(space &s)
{ s.x = -s.x; s.y = -s.y;
s.z = -s.z;}

void main()
{
space s;
s.get(3,-6,9);
s.display();
-s;
s.display();
}
Output:
X = 3, y = -6; z = 9
X = -3, y = 6; z = -9

Overloading unary operators using


friend functions
Here the function being a friend function, it is
not a member of the class, so the private
members of object are not accessible
without the object name from the friend
function.
So the object has to be passed as an
argument.

Overloading binary operators using


member functions
class complex
{
float imag , real;
public:
complex(){..}
complex (float r, float I)
{ x = r; y = i;}
complex operator+ (complex);
void display()
{ cout<<real<< + j<< imag ; }
};

Overloading binary operators using


member functions
complex complex :: operator+ (complex c)
{
complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
void main()
{ complex c1,c2,c3;
c3 = c1 + c2;
//c3 = c1.operator+(c2);
c3.display();
}

Overloading binary operators using


member functions
Note the following features of this function :
It receives only one complex type
argument.
It returns a complex type value. That is it
returns an object.
It is a member function of the class
complex.

Overloading binary operators using


Friend functions
complex operator+ (complex c1 , complex c2)
{
complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
void main()
{ complex c1,c2,c3;
c3 = c1 + c2;
// c3 = operator+(c1,c2);
c3.display();
}

Rules for overloading operators


Only existing operators can be overloaded.
The overloaded operator must have at least one
operand which is of the user defined type.
We cannot change the basic meaning of the
operator.
Overloaded operators follow the syntax rules of
the original operators.
They cannot be overridden.
There are some operators that can not be
overloaded.

Rules for overloading operators


Those operators are -size of operator sizeof
-membership operator . , *.
-scope resolution ::
-conditional operator ?:
We cannot use friend functions while overloading the
following operators.
- assignment operator =
-function call operator ()
-subscripting operator []
-class member access operator ->

Rules for overloading operators


Unary operators when overloaded using
member functions take no explicit arguments ,
but those overloaded with friend functions take
one explicit argument- the object of the relevant
class.
Binary operators when overloaded using
member functions take one explicit argument ,
but those overloaded with friend functions take
two explicit arguments - the objects of the
relevant class.

Runtime polymorphism
At runtime when it is known what class
objects are under consideration , the
appropriate version of the function is
invoked. Since the function is linked with a
particular class much later after the
compilation , this process is termed as
late binding. It is also known as dynamic
binding because the selection of the
appropriate function is done dynamically at
run time.

Runtime polymorphism
Run rime polymorphism
is achieved using
Pointers
class item
{
int code , price ;
public :
void getdata(int c, int p)
{code = c; price = p;}
void display()
{cout << code : <<code;
cout<< price : <<price;}
};

void main()
{
item it;
item *p;
p = &it;
int code,price;
cout<<Enter code and price:;
cin>>code>>price;
p->getdata();
p->display();
}

Pointer to array of objects


void main()
{
item it[3];
item *p;
p = it;
int code,price;
for(int i=0;i<3;i++)
{
cout<<Enter code and price:;
cin>>code>>price;
p->getdata(code,price);
p++;
}

p = it;
for(int i=0;i<3;i++)
{
p->display();
p++;
}
}
Here we are using pointer to array
of objects.
When we use pointers to access
class members -> operator is
used instead of the .(dot )
operator.

Array of Pointer to objects


void main()
{
item it;
item *p[5];
int code, price ,option , i=0;
do
{
p[i] = new item;
cout<<Enter code and price;
cin>>code>>price;
p[i]->getdata ( code, price);
i++;
}while(i<10);

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


{
p[i] -> display();
}
return;
}

Here array of pointers of the type


class are used to access objects.

this pointer
This unique pointer is automatically
passed to a member function when it is
called.
The pointer this acts as an implicit
argument to all the member function.
It points to the implicit object.

this pointer
class person
{
char name[20];
float age;
public:
person( char *s , float a)
{ strcpy ( name , s);
age = a; }
person & person :: greater( person
&x)
{
if( x.age >= age)
return x;
else
return *this
}

void display()
{
cout<<Name : <<name;
cout<<Age : <<age;
}
};
void main()
{
person p1(John , 37.50 ) ;
person p2(Ahmed , 29.50 ) ;
person p3(Hebber , 40.25 ) ;
person p = p1.greater(p3);
p.display();
}

Pointers to Derived Objects


class BC
{
public: int b;
void show()
{cout<<b =<<b <<\n;}
};
class DC : public BC
{
public: int d;
void show()
{cout<<b =<<b <<\n;
cout<<d =<<d <<\n;}
};

void main()
{
BC *bptr , base;
bptr = &base;
bptr->b = 100;
bptr->show();
DC derived;
bptr = &derived;
bptr->b = 200;
bptr->d = 300; //wont work
bptr->show();
}

Pointers to Derived Objects


When we use a base class pointer , make
it point to derived class object , and then
call a function which is present in both
base and derived class , the base class
function gets called.
We cannot use this base class pointer
pointing to the derived class object to
access members of the derived class.

Virtual Functions
class BC
{
public: int b;
virtual void show()
{cout<<b =<<b <<\n;}
};
class DC : public BC
{
public: int d;
void show()
{cout<<b =<<b <<\n;
cout<<d =<<d <<\n;}
};

void main()
{
BC *bptr , base;
bptr = &base;
bptr->b = 100;
bptr->show();
DC derived;
bptr = &derived;
bptr->b = 200;
bptr->d = 300;
bptr->show();
}

Rules for Virtual Functions

Must be members of some class.


Cannot be static members.
Are accessed by using object pointers.
Can be a friend of another class.
Virtual function should be defined in the base
class ,even though it might not be used.
The prototypes of the function in the base class
and in the derived class must be same.
We cannot have virtual constructors but we can
have virtual destructors.

Rules for Virtual Functions


A base class pointer can point to any type
of derived object , but the reverse is not
possible.
The incrementation or decrementation
operator cannot be used with base class
pointer ,pointing to derived object , to point
to the next object.

Rules for Virtual Functions


If a virtual function is defined in the base
class, it need not be necessarily redefined
in the derived class. In such cases, calls
will invoke the base function.

Pure Virtual Functions


The function inside the base class is seldom
used for performing any task.
It only serves as a placeholder.
Such functions are called do nothing
functions. They can be defined as
virtual void display() = 0;
Such functions are called pure virtual
functions.

Abstract base class


A class that has at least one pure virtual
function is called an abstract base class.
The main objective of an abstract base class
is to provide some traits to the derived
classes and to create a base pointer
required for achieving run time
polymorphism.
An object of the ABS cannot be created.

Templates
Templates a new concept which enables us to
define generic classes and functions and thus
provides support for generic programming.
Generic programming is an approach where
generic types are used as parameters in
algorithms so that they work for a variety of
suitable data types and data structures.
A template can be used to create a family of
classes or functions.

Templates
class vector
{
int *v,size;
public :
vector(int m)
{v = new int[size = m];
for(int I = 0; i<size ; i++)
v[i] = 0; }
vector(int *a)
{
for(int i = 0; i<size ; i++)
v[i] = a[i] ;
}
};

void main()
{
int x[3] = {1,2,3};
int y[3] = {4,5,6};
vector v1(3);
vector v2(3);
v1 = x;
v2 = y;
}
This vector class will work only for
int data types.
If we had to generalize it we will
have to use templates.

Templates
Template<class T>
class vector
{
T *v,size;
public :
vector(int m)
{v = new T[size = m];
for(int I = 0; i<size ; i++)
v[i] = 0; }
vector( T *a)
{
for(int i = 0; i<size ; i++)
v[i] = a[i] ;
}
};

void main()
{
int x[3] = {1,2,3};
int y[3] = {4,5,6};
vector <int> v1;
vector <int> v2;
v1 = x;
v2 = y;
}

Templates
Template<class T>
class vector
{
T *v,size;
public :
vector(int m)
{v = new T[size = m];
for(int I = 0; i<size ; i++)
v[i] = 0; }
vector( T *a)
{
for(int i = 0; i<size ; i++)
v[i] = a[i] ;
}
};

void main()
{
int x[3] = {1,2,3};
int y[3] = {4,5,6};
vector <float> v1;
vector <float> v2;
v1 = x;
v2 = y;
}

Two Generic Data Types in a Class


Definition
template<class t1,class t2>
class test
{
t1 a;
t2 b;
public:
test(t1 x, t2 y)
{ a = x; b = y;}
void show()
{ cout<<a = <<a<<b = <<b;}
};

int main()
{
test <float,int> test1(1.23,123);
test <int , char>test2(1.23,123);

test1.show();
test2.show();
return 0;
}

Function Template
template<class T>
void swap(T &x , T &y)
{
T temp = x;
x = y;
y = temp;
}
int main()
{
float a,b;
int x,y;
swap(a,b);
swap(x,y);
}

Functions with Two Generic Data


Types
template<class t1,class t2>
void display( t1 x, t2 y)
{
cout<<x = <<x<<y = <<y;
}
int main()
{
display(1999,ebg);
display(12.34,123);
return 0;
}

Template function with explicit


function
template<class t>
void display(t x)
{
cout<<template display;
}
void display (int x)
{
cout<<Explicit display;
}
int main()
{
display(100);
display(12.34);
display(C);
}

Output :
Explicit display
Template display
Template display

Resolution of overloaded template


or ordinary functions
A template function may be
overloaded either by template
function or an ordinary function.
The overloading resolution may
be resolved as follows:
1. Call an ordinary function which has an exact
match.
2. Call a template function that can be created by
an exact match.
3. Try normal overloading resolution to ordinary
functions and call one that matches.

Non type template arguments


Template <class T , int size>
class array
{
T a[size];
};
void main()
{
array <int ,10> a1;
array <float ,15> a2;
array <char ,12> a3;
}

Exception Handling
Exceptions
Peculiar problems other than logic and
syntax errors.
Run time anomalies or unusual conditions
that a program may encounter while
executing.
Anomalies might include conditions like
division by zero , access to an array
outside bounds, etc.

Exception Handling
Exceptions are of 2 types :
1. Synchronous exceptions
errors such as out of - range or overflow
2. Asynchronous exceptions
errors caused by events beyond the control of
the program such as keyboard interrupt.
The exception handling mechanism in C++ is
designed to handle only synchronous exceptions.

Synchronous Exceptions
Mechanism
Try block
Detects and throws
An exception
Exception
object
Catch block
Catches and handles
the exception

Exceptions Handling Mechanism


C++ exception Handling Mechanism is
basically built on 3 keywords : try , throw
and catch.
Try
1.The keyword try is used to preface a
block of statements which may generate
exceptions. This group of statements is
called try block.

Exceptions Handling Mechanism


Throw
When an exception is detected it is thrown
using throw keyword in the try block.
Catch
A catch block defined by the keyword catch
catches the exception thrown by the throw
statement in the try block and handles it
appropriately.

Exceptions Handling Mechanism


.
try
{
.
throw exception;
.
}
catch(type arg)
{
..
}

//block of statements which detects


// and throws an exception

//catches an exception
//block of statements that handles
// the exception

Exceptions Handling Mechanism


int main()
{
int a,b;
cout<<Enter 2 values;
cin>>a;
cin>>b;
int x = a-b;
try
{
if(x!=0)
cout<<a/x;

else
throw x;
}
catch(int i)
cout<<exception
caught<<x = 0;
cout<<END;
return 0;
}

Function Invoked by try block


throwing exception
Throw point
Throw
Exception

Function that
causes an
Exception
Try block
Invokes a function
that contains an
Exception
Catch block
Catches and handles
the exception

Invoke
function

Function Invoked by try block


throwing exception
type function(arg list) //function with exception
{
throw(object)
//throws exception

}
try
{
.
//invokes the function
}
catch(type arg) //catches an exception
{
..
// the exception
}

Multiple Catch blocks


try
{
.
//invokes the function
}
catch(type1 arg)
//catches an exception
{
..
//catch block 1
}
catch(type2 arg) //catches an exception
{
..
// catch block 2
}
catch(typeN arg)
//catches an exception
{
..
// catch block N
}

Catch all Exceptions


In some situations we may not be able to
anticipate all possible types of exceptions
and therefore may not be able to design all
possible catch handlers.
In such situations we can force all
Exceptionscatch()
{
.
//statements for processing all exp.
}

Working With Files


File
File is a collection of related data stored in a
particular area on the disk.
Need of files
Many real life problems handle large
volumes of data and in such situations we
need to store it in hard disk. The data is
stored in these devices using the concept of files.

Kinds of Data Communication


A program may include either or both kinds
of data communication.
1. Data transfer between console unit and
the program. using cin and cout
objects.
2. Data transfer between the program and
the disk file.- making use of files.

Kinds of Data Communication


External Memory
Data Files
Write data
To files

Get data from


the keyboard

Program + Data

Console Unit
Screen and Keyboard

Read data
from flies

Program File
interaction

Write data
Console program
On
interaction
output screen

Console-program-file interaction

Input and Output Streams


Input Stream
The stream that provides data to the
program is called input stream.
It extracts or reads data from the file.
Output Stream
The stream that receives data from the
program is called output stream.
It inserts or writes data onto the file.

File Input and Output Streams


Read data

Input Stream

Disk Files

Write Data

Data Input

Program

Output Stream

File Input and Output Streams

Data Output

Stream Classes for file Operations


ios
istream

streambuf

iostream file
ostream

iostream
ifstream

fstream

ofstream
filebuf

fstream base
fstream file

Details of File Stream Classes


filebuf
Its purpose is to set the file buffers to read
and write. Contains open() and close() as
members.
fstreambase
Provides operations common to the file
streams. Servers as a base for fstream ,
ifstream and ofstream class.

Details of File Stream Classes


ifstream
Provides input operations . Contains open()
with default input mode. Inherits get() ,
getline() , read() , seekg() and tellg()
functions from istream.
ofstream
Provides output operations. Contains open()
with default output mode. Inherits put() ,
write() , seekp() and tellp()
functions from ostream.
fstream
Provides support for simultaneous input and output operations.

Opening a File
One needs to decide the following things
while opening a file
1. Suitable name of the file.
2. Data type and data structure.
3. Purpose
4. Opening method.

Opening a File
A file can be opened by two ways
1. Using the constructor function
2. Using the member function open() of the
class.

Opening a File with Constructors.


This involves 2 steps1. Create a file stream object to manage a
stream using the appropriate class. That
is ofstream class to create output stream
and ifstream class to create input stream.
2. Initialize the file object with appropriate
file name.
ofstream outfile(results);
Opens a file named results for output.

Reading and Writing in a File


ofstream outfile(results);
ifstream infile(test);
outfile<<TOTAL;
infile>>number;
Here we are reading from test file and
writing into results file

Working with Single File using


Constructors
int main()
{
ofstream outf(ITEM);
// writing into file ITEM
cout<<Enter Name:;
char name[20];
cin>>name;
outf<<name;
outf.close();

//reading from the same file


ifstream inf(ITEM);
inf>>name;
inf.close();
//writing the read name on
// the output screen.
cout<<Name : <<name;
}

Working with Multiple File using


open() function.
int main()
{
ofstream outf;
outf.open(country);
// writing into file Country
outf<<USA;
outf<<United Kingdom;
outf.close();
// writing into file Capital
outf.open(Capital);
outf<<Washington;
outf<<London;
outf.close();

char str[20];
ifstream inf1 , inf 2;
inf1.open(Country);
inf2.open(Capital);
while(inf1)
{ inf1>>str;
cout<<str;
}
while(inf2)
{ inf2>>str;
cout<<str;
}
inf1.close();
inf1.close();
}

Open() file mode

ios::in - for reading only


ios::out - for writing only
ios::app - append to end of file
ios::ate - go to end of file on opening.
ios::nocreate open fails if file does not exist
ios::noreplace opens files if the file already
exists
ios::trunc -deletes the contents of the file if the
file already exists.
ios::binary - Binary File

File Pointers
Each file has two associated pointers known
as file pointers
1. Input or get pointer. It is used for reading
the contents of a given file.
2. Output or put pointer. It is used for
writing to a given file location.

Functions for Manipulation of File


Pointers
seekg() - moves the get(input) pointer to a
specified location
seekg(offset, refposition);
seekp() - moves the put(output) pointer to a
specified location
seekp(offset, refposition);
tellg() gives the current position of the
get(input ) pointer
tellp() gives the current position of the
put(output ) pointer

Functions for Manipulation of File


Pointers
The refposition takes one of the following
three constants
1. ios::beg - start of the file
2. ios::cur - current position of the file
3. ios::end - end of the file

Functions for Manipulation of File


Pointers
Seek call
fout.seekg(0,ios::beg)
fout.seekg(0,ios::cur)

Action
go to start
stay at the current
location.
fout.seekg(m,ios::beg) move to (m+1)th
byte from the beg.
fout.seekg(-m,ios::end) go backward by m
bytes from the end

io operations on Binary Files.


write() and read( functions
1. They handle data in the binary mode.
2. Syntaxinfile.read((char*)&V , sizeof(V));
outfile.write((char*)&V , sizeof(V));
Both these functions take two arguments
1. address of the variable V
2. no of bytes occupied by it.

Reading and Writing Class Objects


class student
{
int rno;
char name[20];
public:
void read();
void display();
};

void student::read()
{
cout<<Enter roll no:;
cin>>rno;
cout<<Enter name :;
cin>>name;
}
void student::display()
{
cout<<RollNo : <<rno;
cout<<Name : <<name;
}

Reading and Writing Class Objects


void main()
{
student s[3];
ofstream outf;
outf.open(students);
cout<<Enter details for 3
students : ;
for(int i=0;i<3;i++)
{
s[i].read();
outf.write((char*)&s[i], sizeof(s[i]));
}

outf.close();
ifstream inf;
inf.open(students);
for(int i=0;i<3;i++)
{
outf.read((char*)&s[i], sizeof(s[i]));
s[i].display()
}
inf.close();
}

Operations on a file containing


records
The following are the important operations
that have to be performed on the file
1. Writing records in the file.
2. Reading records from the file.
3. Modifying an existing record from a file.
4. Adding a new item to a file.
5. Deleting an existing item.

Error Handling With files


One of the following things may happen
when dealing with files
1. A file being opened for reading does not exist.
2. A filename used for a new file already exists.
3. Reading past end of file.
4. No space in the memory for creating more
files.
5. Using invalid file name.
6. Trying to perform an operation for which we
have not opened the file.

Error Handling Functions


Function

Return value and meaning

1. eof()

returns true if EOF has been


encountered while reading
otherwise returns false.
returns true if an input or an
output operation has failed.

2. fail()

Error Handling Functions


Function Return value and meaning
3. bad()
returns true if an invalid
operation
has occurred or
unrecoverable operation
has
occurred, returns false if a
recoverable operation has occurred.
4. good() returns true if no error has occurred
and false when no further operations can be
further carried out.

Error Handling Functions


ifstream infile;
infile.open(ABC);
while(!infile.fail())
{

//process the file.


}
if(infile.eof())
{
//terminate program
//normally
}

else
{
if(infile.bad())
{
//report fatal error
}
else
{
infile.clear();
}
}
clear() resets the error state so
that further operations can be
attempted.

Standard Template Library


The collection of generic classes and
functions is called standard template
library. (STL)
STL contains several components. But at
its core are three key components
1. Containers
2. algorithms
3. iterators

Standard Template Library


Container
It is an object that actually stores data.
It is a way data is organized in memory.
The STL containers are implemented by
template classes and therefore can be
easily customized to hold different data
types.

Standard Template Library


Algorithm
It is procedure that is used to process data
contained in the containers.
STL includes many different kinds of
algorithms to provide support to tasks
such as initializing , searching , copying ,
sorting , merging.
Algorithms are implemented using
template functions.

Standard Template Library


Iterators
it is an object that points to an element in a
container.
They are used to move through the contents of
the container.
Iterators are used just like pointers. We can
increment and decrement them.
They connect algorithms with containers and
play a key role in manipulation of data stored in
the containers.

Categories of Containers
Containers

Sequence
Containers

Associative
Containers

Derived
Containers

Vector
Deque
List

Set map
Multiset
Map
Multimap

Stack
Queue
Priority queue

Containers
Vector
A dynamic array.
Allows insertions and deletions at back.
Allows direct access to any element.
Header file - <vector>
Iterator random access.

Containers
List
A bidirectional ,linear list.
Allows insertions and deletions anywhere.
Header file - <list>
Iterator bidirectional.

Containers
Deque
A double ended queue.
Allows insertions and deletions at both the
ends.
Permits direct access to any element.
Header file - <deque>.
Iterator random access.

Containers
Set
An associative container for storing unique
sets.
Allows rapid look up.
Header file - <set>.
Iterator bidirectional.

Containers
Multiset
An associate container for storing non
unique sets.
No duplicates allowed.
Header file - <set>.
Iterator bidirectional.

Containers
Map
An associate container for storing unique
key/value pairs.
Each key is associated with only one value.
One to one mapping.
Allows key based look up.
Header file - <map>.
Iterator bidirectional.

Containers
Multimap
An associate container for storing key/value
pairs.
Each key is associated with more than one
value.
One to many mapping.
Allows key based look up.
Header file - <map>.
Iterator bidirectional.

Containers
Stack
A standard stack.
Last in first out (LIFO).
Header file - <stack>.
No iterator.
Queue
A standard queue.
First in first out (FIFO).
Header file - <queue>.
No iterator.

Containers
Priority queue
A priority queue.
The first element out is always the highest
priority element.
Header file - <queue>.
No iterator.

Comparison of sequence
Containers
Container random
access

I/D in
middle

I/D at end

Vector
List
Deque

slow
fast
slow

fast at back
fast at front
fast at both
ends

fast
slow
fast

Associative Containers
They are designed to support direct access
to elements using keys.
They are not sequential.
There are four types
1. Set
2. Multiset
3. Map
4. Multimap

Derived Containers
The STL provides three derived containers
namely stack , queue and priority_queue.
These are also known as container adapter.
Stack , queue and priority_queue can be created
from different sequence containers. The derived
containers do not support iterators and therefore
we cannot use them for data manipulation.
They support two functions push() and pop()
for performing deleting and inserting operations.

Algorithms
They are functions that can be used
across a variety of containers for
processing their contents.
STL algorithms reinforce the philosophy of
reusability.
We must include <algorithm> in our
program.

Iterators
They behave like pointers and are used to
access container elements.
They are often used to traverse from one
element to another , a process known as
iterating through the container.

Iterators
There are five types of iterators
Input
1.Access method linear
2. Direction of movement forward only
3. I/O capability read only
4. Remark cannot be saved

Iterators
There are five types of iterators
Output
1.Access method linear
2. Direction of movement forward only
3. I/O capability write only
4. Remark cannot be saved

Iterators
There are five types of iterators
Forward
1.Access method linear
2. Direction of movement forward only
3. I/O capability read/write only
4. Remark can be saved

Iterators
There are five types of iterators
Bidirectional
1.Access method linear
2. Direction of movement forward and
backward
3. I/O capability read/write
4. Remark can be saved

Iterators
There are five types of iterators
Random
1.Access method random
2. Direction of movement forward and
backward
3. I/O capability read/write
4. Remark can be saved

You might also like