Sie sind auf Seite 1von 58

OBJECT ORIENTED PROGRAMMING CONCEPTS

C++ is an object oriented programming language. It was developed by Bjarne stroustrup at


AT&T Bell Laboratories in Murray Hill,New Jersay,USA,in the early 1980s.
Stroustrup initially called the new language C with classes,later in 1983.the name was
changed to C++.C++ is a superset of c.
BASIC CONCEPTS
*Object
*Classes
*Data abstraction
*Encapsulation
*Inheritance
*Polymorphism
*Dynaming binding
*Message Passing
1.Object:
Object are the basic run time entities. They may represent a Person,Place,a bank
account or any item that the Program to handle.
For ex:
Reprehending an object
Object: STUDENT
DATA:
Name
Date of birth
Marks.
FUNCTION:
Total
Average
Display


Classes:
A class is a User defined data type. It is way to bind data and functions together
.It encapsulate data and functions into a single Unit.
Once a class has been defined, we can create any number of objects belonging to that class.
Data Abstraction:
Abstraction refers to the act of refers ending essential features
without including the background details or explanations.
The classes use the concept of data abstraction they are Known as Abstract Data
Types(ADT).
Encapsulation:
The wrapping up of data and functions into a single Unit is Known as
encapsulation.
The data is not accessible to the outside world, And only those functions which are Wrapped
in the class can access it.
These functions provide the interface between the objects data and the program. This
insulation of the data from direct access by the programs is called data hiding (or)
information hiding.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties
of objects of another class.
In oop the Concept of inheritance provides the idea of reusability.
This means that we can add additional features to an existing class without modifying it. This
is possible by deriving a new class will have the Combined features of both the class.
EX :

Bird
Flying bird No flying bird
Parrot Penguin

Polymorphism:
Polymorphism ,a Greek term, means the ability to take more than one
form.
An operation may exhibit different behaviours in different instance. This behaviour depends
upon the types of data and number of argument used in the operation.
It has two types.
1.Operator Overloading
2.Function Overloading.
1.Operator Overloading:
The process of making are operator to exhibit different
behaviours in different instances is Known as operator overloading.
2.Function Overloading:
The process of making an operation to exhibit different
behaviour in different instances is Known as Function Overloading
Shape Draw()
Circle Object
Draw(circle)
Box Object
Draw(box)
Triangle Object
Draw(triangle)
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not Known
until the time of the call at run-time .
Message Passing:
An object-object program consists of a set of objects that
communicate with each other.
Objects communicate with one another by sending and receiving information.
Benefits of oop:
The principal advantages are:
1.The principal of data hiding helps the programmer to build secure programs.
2. Through inheritance ,We can eliminate redundant code and extend the use of
existing classes.
3.Object oriented system can be easily upgraded from small to large system.
4. Software complexing can be easily managed.
Object Oriented Programming Paradigm:
Object Oriented Programming allows
decomposition of a problem into a number of entities called objects and then builds data and
functions around there objects.
The organization of data and function in Object programming Program.
Object A
Data
Functions

Object B
Data
Functions

Object C
Function
Data

Some of the important features of Object Oriented Programming are:
1.Emphasis is an data rather than procedure
2.Programs are divided into what are Known as objects.
3.Functions that operate on the data of an object are tied together in the data structure.
4.Data in hidden and cannot be accessed by external functions.
5.Objects may Communicate with each other through functions.
6.New data and functions can be easily added whenever necessary.
7.Follows bottom up approach in program design.
Thus an object is considered to be a Partitioned area of computer memory partitions are
independent, the objects can be used in a variety of different programs without modification.
Application of oop:
1.Real time systems.
2.Simulation and modelling.
3.Object Oriented Database.
4.AI and expert systems .
5.CAD/CAM system.
6.Newral Networks and parallel programming
Program Elements:.
A program is composed of elements called tokens, Which are
collections of characters that form the basic vocabulary the compiler recognizer.
The character set includes
1.Lower case and Uppercase alphabet.
a....z and A...Z.
2.Digits....0.....9.
3.Operators +, *,=,<,>.
4.Punctuation : ; . .
Comments:
Single Line Comment. //
Double line comment . /*.......*/
Keywords:
Keywords are reserved words. That meaning cannot be changed during the
execution of the programs. Keywords are basic building blocks of programs.
EX:Virtual,Inline,Template.
Identifiers:
Identifier refers to the name of Variable,Constants,arrays and Pointer, It has
the following rules.
1.First letter must be a char.
2,Special char not allowed except underscore.
3.Uppercase and Lowercase letters are distinct.
EX:exam_date.
Literals:
Literals are Constant values.That values do not change during the execution of the
program Types of Literals.
Literals
Numeric Literals Char Literals
Integer Literals Single Char Literals
Real Literals String Literals
Escape Sequence:
Non printing special charecters are called escape sequence.It contains
\Char.
EX:
\n-new line.
\t-tab.
Operators:
Operators is a symbol that the compiler to perform certain mathematical logical
Operators.
Types of Operators:
1. Arithmetic.
2. Relational.
3. Logical
4. Assignment
5.Increment &Decrement
6.Bitwise Operator
7.Special Operator.
Other new Operator are:
:: - Scope Resolution Operator.
::*- Pointer to Member Declaration
->*}- Pointer to Member Operator
Delete Memory release operator.
Endl line feed operator.
New memory allocation operator.
Setw field width operator
<<-Insertion Operator
>>-Extraction Operator.
C++ Streams:
A stream in a sequence of bytes. It acts either as a source from which the
input data can be obtained or as a destination to which the output data cn be send.
Cin>> Data Stream
Input Device Output Device







Classes &Objects:
A class is a way to bind the data and its associated functions
together ie) It encapsulate data and functions together into a single Unit.
A class specification has 2 Parts.
1.Class declaration
2.Class function definition.
Syntax:
Class Classname
{
Private:
Variable declaration;
Function declaration;
Public:
Variable declaration;
Function declaration;
};
Where, Class-is a Keyword
Class is a user defined name Body of the class enclosed with braces and
terminated with semicolon.
The class body contains the declaration of variables, functions,These variables are
collectively called members and the function are called member function
Input Stream Output Stream
Program
The keyword private and public are known as visibility labels and it should end with
color.
By default all the members are private.

Creating objects :
Objects ars instantes of clons . our a class hasbeen declased ne can create
Object of the clans by using tha clans home.
Accessing clans members:
A Clans members can be accessed by using the objets of that clans
Syn.
Objecthame. Function name cactual arguments;
Defining member function:
Member functions can de fined in two plaus.
1.In side clans definition.
2. outside clans definition.
Outside definition:
Member functions that are declased inside of the clans con be defined
separately outside of the class.
Syn.
Returntybe clansname : : funetion name (arguments)
{
Funetion body
}

The symbol : : in called scope resolution operator

The membership label class name : : tells the compiles that the funetion
funetion name belongs to the clans class name

EX:
# INCLUDE <IOSTREAM.H>
Class item
{
Int number ;
Float cost ;
Public :
Void get data (int a , float b):- inside definition

{
Cout<<number<<number<<m;
Cout<<cost<<cost<<in; - inside definition
}
};

Void item :: get data ( int a , float b )
{
Number = a ;
Cost = b ;
}

Int main( )
{
Iten X: _ cueating objects
X. get data (100,50.50);
X.putdata ( );
itamY : _ creating anotha objects
Y.getdata (200,75.75 )
Y.putdata ( );
Retu
}






OBJECT AS FUNCTION ARGUMENTS:
An object may be used as a function argument . this can be done in two ways.
1.a copy of the entire is pssed to the function
2.ouly the addess of the object is tranferd to the function
Clans name : item
Nember funetion name :getdata ( )
Putdata()
Object name : X, Y.
MEMBERS : NUMBER, COST,
The first method in called pass be value.
Ex) a copy of the object in passed to the funtion , any chauges made to the object inside
trhe funtion do not affeet the object uesd to
The second method is calld pass by refecen
Ex) the addess of the object is possed vto the funetion , any cheuges made to the object
inside the funetion will refleet in the objecd
Ex)
# include < iostneam. H >
Clens time
{
Int hours ;
Int minutes ;
Public :
Void get time (int h , int m)
Hours =h;
Minutes =m;
}
Viod put time ( )
{
Cout <<hours<<hours and ;
Cout <<minutes<<\n;
}
Void sum (time , time );
};
Void time : : sum (time t1 , time t2 )
{
Minutes = t1 . minutes + t2 . minutes ;
Hours = minutes /60 ;
Minutes = minutes % 60 ;
Hours = hours + t1 . hours + t2 hours ;
}
Int main ( )
{
Time T1 , T2 ,T3 ,;
T1 , get time ( 2 , 45 );
T2 , get time ( 3 , 30 );
T3 , sum (T1 ,T2 );
COUT << T1 = T1 . put time ( ) ;
COUT < <T2 = T2 . put time ( ) ;
COIT < < T3 = T3 . put time ( ) ;
Return 0
}
Friend Function:
A non-member function access to the private members of a class
by using a friend function.
A friend function has to access all private and protected members of
the class.
A friend function should have its protected within class,preceeding.it
with a keyword friend .
SYN:
Class classname
{
Public:
- - -
- - -
Friend void xyz(void);
};
Characteristics of a friend function:
1.It is not in the scope of the class.
2.It cannot be called using the object of that class.
3.It can be declared either in the public or the private part of a clss without affecting its
meaning.
4.Usully,it has the objects s arguments.
EX:(RETURNING OBJECTS):
#include<iostream.h>
Class complex
{
Float x;
Float y;
Public:
Void input(float real,float img)
{
x=real;
y=img;
}
friend Complex sum(Complex,Complex);
void show(Complex);
};
Complex Sum(Complex c1,Complex c2)
{
Complex c3;
C3.x=c1.x+c2.x;
C3.y=c1.y+c2.y;
return(c3);
}
void Complex::show()
{
Cout<<x<<+j<<y<<\n;
}
int main()
{
Complex A,B,C;
A.input(3.1,5.65);
B.input(2.75,1.2)
C=Sum(A,B);
Cout<<A=;
A.show();
Cout<<B=;
B.show();
Cout<<C=;
C.show();
return 0;
}
Inline Function:
An inline function in a function that is expanded inline when it in
invoked.ie) Compiler replaces the function call with the corresponding function
Code.
Syn:
Inline function header
{
function body
}
Advantage:
1.Inline expansion makes a program run faster. some of the situation where inline expansion
maynot work.
2.If the function contain static variables.
3.If inline function are recursive.
4.If the function contains a loop, switch(or) goto
Ex:
#include<iostream.h>
Inline float mul(float x,float y)
{
return(p/q);
{
inline double div(double p,double q)
{
return (p/q);
}
int main()
{
float a=12.345;
float b=9.82;
cout<<mul(a,b)<<\n;
cout<<div(a,b)<<\n;
return 0;
}
Constructor:
A constructor is a special member function.
A constructor name is same as the class name.The constructor is invoked whenever an object
of its associated class is created.
Characteristics:
1.They should be declared in the public section.
2.They are invoked automatically when the objects are created.
3.They do not hava return type.
4.They cannot be inherited.
5.They can hav default arguments.
Types of Constructor:
1.Default Constructor
2.Paremeterized Constructor.
3. Copy Constructor.
1. Default Constructor:
A Constructor that accepts no parameter is called the default
constructor If no such Constructor is defind,then the Compile supplies a default Constructor
2. Parameterized Constructor:
If the constructor have argument then it is called
paremeterized constructor.
When the constructor is parameterized,we must provide appropriate arguments for the
constructor
This cn be done in two ways.
1.By calling the constructor explicitly.
2.By clling the constructor implicitly.
Destructor:
A destructor is used to destroy the objects that have been created
By a constructor.
The destructor is member function whose name is same
As the class name but it proceeded by tilde.
A destructor never takes any argument and it did not return any value.
It will be invoked implicitly by the complier upon exit from the program to cleanup storage
that in no longer accessible .
ADV:
Releases memory space for future use.
EX:
#include<iostream.h>
#include<conio.h>
Class length
{
Int feet, inches;
Public:
length()
{
}
length(int f,int i)
{
feet=f;
inches=i;
}
Void print()
{
Cout<<length is<< ;
Cout<<feet=<<feet;
Cout<<inches=<<inches;
}
Void Sum(length ,length b)
{
feet=a,feet+b.feet;
inches =a,inches+b.inches;
while(inches>-12)
{
inches =inches-12;
feet++;
}
~length()
{
Cout<<this function destroyed;
}
};
int main()
{
Clrscr();
Cout<<constructor and destructor;
Cout<<---------------;
Length l1(6,3),l2(5,4),l3;
l3.sum(l1,l2);
cout<<l1=;l1.print();
cout<<l2=;l2.print();
cout<<l3=;l3.print();
return 0;
}
Copy Constructor:
A copy constructor takes a refers to an object of the same class as itself
as an argument.
A copy constructor is used to declare and initialize an object from another
object A reference variables has been used as an argument to the copy constructor.
We cannot pass the argument by value to a copy constructor.
EX:
#include<iostream.h>
#include<conio.h>
class code
{
Int id;
Public:
Code()
{
}
Code(int a)
{
Id=a;
}
Code(code &x)
{
Id=x.id;
}
Void display()
{
Cout<<id;
}
};
Int main()
{
Code A(100);
Code B(A);
Code C=A;
Cout<<\n id of A:;A.display();
Cout<<\n id of B:;C.display();
Return 0;
}
Static members:
A data member of a class cn be qualified as static the properties of a
static.the properties of a static member variables is similer to a c static variable.
CHAR:
1)It is initialized to zero when the first object of its class is created,no other initialize is
permitted.
2)only one copy of the member is created for the entires class and it is shared by all the
objects of that class, no matter how many objects re created.
3)It is visible only within the class,but its lifetime in it the entire program.
Ex:
#include<iostream.h>
Class item
{
Static int count;
Int number;
Public:
Void getdata(int a)
{
Number=a;
Count++;
}
Void getcount()
{
Count<<count;
Count<<count<<\n;
}
};
Int item::count;
Int main()
{
Item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getcount(100);
b.getcount(200);
c.getcount(300);
cout<<after reding data<<\n;
a.getcount();
b.getcount();
c.getcount();
return 0;
}
Object 1
100
Object 2
200
Object 3
300
count
3
Static member function:
A member function tht in declared as static has the following
propertics.
1)A static function can have access to only other static members declared in the same class.
2)A satic member function can be called sing the class name.
EX:
#include<iostream.h>
Class tral
{
Static int able,tot;
Public:
Static void sumdata()
{
If(able!=0)
{
Cout<<\n it the available seats:<<able;
}
Else
{
Cout<<\n\t the seat in not available;
}
}
Static void sumdata()
{
Tot++;
Ble--;
If(tot<=60)
{
Cout<<your seat reserved successfully;
Cout<<\n\t the seat no is<<tot;
Cout<<\n \t remaining seats are<<able;
}
}
};
Int tral::able=60;
Int tral::tot;
Void main()
{
Int ch,tot;
Char ch1;
Clrscr();
Cout<<\n \t universed travels;
Cout<<\n\t main menu;
Cout<<\n \t 1.enquiry;
Cout<<\n \t 2.reservation;
Cout<<\n\t 3.exit;
Do
{
Cout<<\n\t enter your choice;
Cin>>ch
Switch(ch)
{
Cse 1:
Tral::sumdata();
Break
Case 2:
Trl::sum1data();
Break;
}
Cout<<\n\t do you want to continue(y/n);
Cin>>ch1;

}
While(ch1==y);
Getch();
}
THIS POINTER:
When a member function in called it in automatically passed an implicit
argument that in a pointer to the invoking object.
Ie)The object on which the function in called.This pointer is called this pointer.
1)The this pointer is vewry importent when operator are overloaded.
2)Friend function are not member of a class and therefore they are not passed to this pointer.
3)The this pointer is automatically passed to all member functuion.
4)Static member function do not have a this pointer.
EX:
#include<iostream.h>
Class pwr
{
Double b;
Int e;
Double val;
Public:
Pur(double base,int exp);
Double get_pwr()
{
Return val;
}
};
Pur::pur(double base,int exp)
{
This->b=base;
This->e=exp;
This->val=1;
If(exp==0) return;
For(;exp>0;exp--)
{
This->val=this->val* this->b;
}
}
Int main()
{
Pur x(4.0,2),y(2.5,1),z(5.7,0);
Cout<<x.gety_pur()<< ;
Cout<<y.gety_pur()<< ;
Cout<<z.gety_pur()<<\n ;
Return 0;
}
REFERENCE SEMANTICS:
C++ introduces a new kind of variable known as
reference variable.
A reference variable provides an (alternative name) for a previously defined variable.
SYN:
Data type &reference name=variable name;
EX:
INT TOTAL=100;
(OR)
INT &SUM=TOTAL;
Here sum in the alternative name declared to represent the variable total.Both the variables
refers to the same data in the memory.
A reference variable must be initialized at the time of declaration.
Here is in not are address operator.
EX:
#include<iostream.h>
Int main()
{
Int a;
Int &ref=a;
A=10;
Cout<<a<< <<ref<<\n;
Ref=100;
Cout<<a<< <<ref<<\n;
Int b=19;
Ref=b;
Cout<<a<< <<ref<<\n;
Ref--;
Cout<<a<< <<reff<<\n;
Return 0;
}
O/P:
10 10
100 100
19 19
18 18
UNIT 3[POLYMORPHISM]
OVERLOADING:
The mechanism of giving such special meaning to an operator is known as
operator overloading.
Overloading operator:
i)operator in c++
<<-Insertion operator
>>-Extraction operator
::-Scope resolution operator
::*-Pointer to member declaratory
->*-Pointer to member operator
.*-Pointer to member operator.
In addition .c++ allows us to provide new definition to some of the buit in operator.
Ie)we can give serv meaning to an operator,depending upon the types of argument used.
SOME OF THE OPERATOR CANNOT OVERLOAD.
1- sizeof-sizeof
2- . membership operator
3-.* pointer to member oprerator
4-:: scope resolution operator
5-?: conditional operator
We cannot use friend function to overload certain operator.
1. = Assignment operator
2. () function call operator
3. [] subscripting operator
4. -> class member access operator.
RULES FOR OVERLOADING OPERATORS.
1.one exising operators can be overloaded new operator cannot be created.
2.we cannot change the basic meaning of an operator.
3.overloaded operator follows the syntax rules of the original operator.
4.some operator cannot be overloaded.
5.unary operator,overloaded by means of a member function take no
explicit argument but,those overloaded by means of a friend function take one reference
argument.
6.binary operator overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit argument.
GENERAL FORM OF OPERATOR OVERLOADING:
Return type classname:: operator op(arg list)
{
- - - - -
- - - - -
}
Operator-keyword
Op-operator to be overloaded
Operator function must be either member function (or) friend function.
A basic difference between them is that a friend function will have only one argument for
unary operator, and 2 for binary operator.
While a member function has no argument for unary operator and only one for binary
operator.
OVERLOADINNG UNARY OPERATOR:
Here we take minus operator this operator
changes the sign of the operator when allied to a basic data item.
EX:
#include<iostream.h>
Class space
{
Int x,y,z;
Public:
Void getdata(int a,int b,int c);
Void display(void);
Void operator ();
};
Void space::getdata(int a,int b,int c)
{
X=a;
Y=b;
Z=c;
}
Void space::display(void)
{
Cout<<x<< ;
Cout<<y<< ;
Cout<<z<<\n;
Void space::operator-()
{
X=-x;
Y=-y;
Z=-z;
}
Int main()
{
Space S;
S.getdata(10,-20,30);
Cout<<S:;
S.display();
-S;
Cout<<S:;
S.display();
Return 0;
}
O/P:
S:10 -20 30
S:-10 20 -30
OVERLOADING BINARY OPERATOR:
#include <iostream.h>
Class complex
{
Float x,,y;
Public:
Complex(){}
Complex(float real,float img)
{
X=real;
Y=img;
}
Complex operator+(complex);
Void display();
};
Complex complex::operator+(complex c)
{
Complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
Void complex::display(void)
{
Cout<<x<<+j<<y<<\n;
}
Int main()
{
Complex c1,c2,c3;
C1=complex(2.5,3.5);
C2=complex(1.6,2.7);
C2=c1+c2;
Cout<<c1=;c1.display();
Cout<<c2=;c2.display();
Cout<<c3=;c3.display();
return 0;
}
O/P
C1=2.5+J3.5
C2=1.6+J2.7
C3=4.1+J6.2.
OPERATOR OVERLOADING USING FRIEND FUNCTION:
A friend function that overloads a binary operator has two parameters and operator has one
parameter.
#include<iostream.h>
Class loc
{
Int longitude,latitude;
Public:
Loc(){}
Loc(int lg,int lt)
{
Longitude=lg;
Latitude=lt;
}
Void show()
{
Cout<<longitude<< ;
Cout
<<latitude<<\n;
}
Friend loc operator +(loc op1,loc op2);
};
Operator+(loc op1,loc op2)
{
temp;
temp .lg=op1.lg+op2.lg;
temp.lt=op1.lt+op2.lt;
return(temp);
}
Int main()
{
Loc p,q,z;
P=loc(5,2);
Q=loc(6,4);
Z=p+q;
Loc ob1(10,20),ob2(5,30);
Ob1=ob1+ob2;
Ob1.show();
return 0;
}
Cout<<p=;p.show();
Cout<<q=;q.show();
out<<z=;z.show();
return 0;
}
FUNCTION SELECTION:
The process of making a function to exhibit different behaviours in different instance is
called function overloadind.
A function call first matches the prototype having the smae number and type of
arguments and then calls the appropriate function for execution.
EX:
#include<iostream.h>
Int volume(int);
Double volume(double,int );
Long volume (long,int,int);
Int main ()
{
Cout<<volume(10)<<\n;
Cout<<volume(2,5,6)<<\n;
Cout<<volume(100,75,15)<<\n;
return 0;
}
Int volume(int s)
{
return(s*s*s);
}
Double volume(double r,int h)
{
return(3.14*r*r*h);
}
long volume(long l,int b,int h)
{
return(l*b*h);
}
POINTER OPERATOR:
The structure pointer operator -> is overloaded
A pointer is a variable it stores the address variable.
DECLARING A POINTER:
SYN:
Datatype * pointername;
PINTER TO OBJECTS;
When accessing members of a class a pointer to an object, use
the arrow operator instend of the dot operator.
EX:
#include<iostream.h>
Class c;
{
Int i;
Public:
C1(int j_
{
I=j;
}
Int get()
{
return 1;
}
};
Int main()
{
C1 ob(88),*p;
P=&ob;
Cout<<p->get();
return 0;
}
Pointer to class members:
A special type of pointer that pointer generally to a
member of a class is called a pointer to a class member or a pointer to member,here the
operators
.*(or)* is used
EX:
#include<iostream.h>
Class c1
{
Public:
C1(int i)
{
Val=i;
Int double-val()
{
return val+val;
}
};
Int main()
{
Int c1::*data;
Int(c1::*fun(),);
C` ob1(1),ob2(2);
C1*p1,*p2;
P1=&ob1;
P2=&ob2;
Data=&c1::val;
Func=&c1::double_val;
Cout<<here are values;
Cout<<p1->*data<< <p2->*data<<\n;
Cout<<here they are double3d;
Cout<<(p1->*func){()<< ;
Cout<<(p2->*func)()<<\n);
return 0;
}
VISITATION:
Conventional programming uses the for st as its preferred means of
structuring iteration,especially when processing arrays is called visitation.
//visit each a[i] and do something
For(i=0;i<size;++i)
Sum +=a[i];
The homogeneous aggregate a[] is processed element by element.
The for st specifies a specific order of visitation and is controlled by an inndex1,which
in visibly mmodifed.
The order of visitation and the index used aree generally details of implementation that
do not affect the computation.
Here in an alternative coding that performs the same computation:
For(j=size-1;j>=0;--j)
Sum+=a[jj];
CONTRAINERS:
A container in an object that actually stores data.it is a way data
in organized in memory.
The stl defines containers which are grouped into three categories.
CONTAINERS
Associate
Containers
*)set

*)multiset

*)map

*)multimap
Derived
Containters

*)stack

*)queue

*)priority-
queue
Associate
Containers
*)set

*)multiset

*)map

*)multimap

CONTAINER DESCRIPTION HEADERFILE ITERATOR
1.vector A dynamic array
allows insertions and
deletions at back
permits direct access
to any element
<vector> Random access
2.list A bidirectional,linear
list.allows insertions
and deletions
anywhere
<list> bidirectional
3.deque A double ended
queue.allows
insertions and
deletions at both the
ends permits direct
access to any element
<deque> Random access
4.set An associative
container for storing
unique sets(no
duplicates allowed)
<set> Bidirectional
5.multiset An associative
container for storing
non-unique
sets.(duplicates
allowed)
<set> Bidirectional

6.map An associative
container for storing
unique key/value
pairs.each key is
associated with only
one value
<map> Bidirectional

7.multimap An associate
containter for storing
key/value pairs in
which one key may
be associated with
more then one
value(one to many
mapping)
<map> Bidirectional

8.stack


A standard stack.last-
in-first out(LIFO)


<stack>


No iterator


9.priority queue A priority queue,the
first element out in
always the highest
priority element
<queue> No iterator
10.Stack A standard stack last-
in first out(LIFO)
<stack> No iterator


Each container class defines a set of functions that can be used to manipulate its contents.
SEQUENCE CONTAINERS:
Sequence containers store elements in a linear
sequence,like a like.
ELEMENT
0
ELEMENT
1
ELEMENT
2
ELEMENT
3
Each element is related to other elements by its position along the line.they all expand
themselves to allow insertion of elements and all of them support a number of operations on
them.
STL provides three types of sequence containers
1.vector
2.list
3.deque
Element in all these containers can be accessed using an iterator.the difference between the
three of them in related to only their performance.
COMPARISON
CONTAINER RANDOM ACCESS INSERTION
DELETION IN THE
MIDDLE
INSERTION (OR)
DELETION AT THE
END
Vector
List
deque
Fast
Slow
Fast
Slow
Fast
Slow
Fast at back
Fast at front
Fast at both the ends.
ASSOCIATIVE CONTAINERS:
Associative contsainers are designed to support direct
access to elements using keys they are not sequential.
There are four types of associative containers
1.set
2.multiset
3.map
4.multimap
All these containers store data in a structure called tree which facilitates fast
searching,deletion,and insertion
DISADV:
These are very slow for random access and inefficient for sorting.
SET &MULTISET:
It can store a number of items and provide operations for manipulating
them using the values asa the keys.
EX:
A set might store objects of the student class which are ordered alphabetically using names
as keys.
DIFFERENCE:
Multiset allows duplicate items which a set does not.
MAP &MULTIMAP:
It can store pair of items,one called the key and the other called the
value.
DIFFERENCE:
Map allows only one key for a given value to be stored while multimap
permits multiple keys.
DERIVED CONTAINERS:
The STL provides three derived containers
namely,stack,queue,and priority queue. These are also known as container adaptors.
The derived container do not support iterators and therefore we cannot use them for data
manipulation
It support 2 member functions.
1.pop()-delete operation
2.push()-insert operation
Application of container classes:
1.vector
2.list
3.map
VECTOR:
The vector is the most widely used container it stores elements in contiguous
memory location and direct access using[] operation.
ADVANTAGE:
A vector can change its size dynamically and therefore allocation memory as
needed at run time.
EX:
#include<iostream.h>
#include<vector>
Void display(vector<int>&v)
{
For(int i=0;i<v.size();i++)
{
Cout<<v[i]<< ;
}
Cout<<\n;
}
Int main()
{
Vector<int>v;
Cout<<initial size=<<v.size()<<\n;
Int x;
Cout<<enter five integer values;
For(int i=0;i<5;i++)
{
Cin>>x;
v.push_back(x);
}
Cout<<size after adding 5 values;
Cout<<v.size()<<\n;
Cou<<current contents:\n;
Display(v);
//add one more value
v.pushback(6.6);
//display size and contents
Cout<<\nsize=<<v.size()<<\n;
Cout<<contents now:\n;
Display(v);
//inserting elements
Vector<int>::iterator itr=v.begin();
Itr=itr+3;
v.insert(itr,1.9);
//display the contents
Cout<<\n contents after inserting \n;
Display(v);
//remving 4
th
&5
th
element
v.erase(v.begin()+3,v.begin()+5);
//display the contents
Cout<<contents after deletion:\n;
Display(v);
Cout<<end\n;
return 0;
}
LIST &LIST ITERATORS:
The list in another container that is popularly used.it supports a
bidirectional ,linear list and provides an efficient implement for deletion and insertion
operations.
A list can be accessed sequentially only any algorithm that requires input,output,forward or
bidirectional iterators can operate on a list.
Iterader file<list>must be included to use the container class list.
IMPORTANT MEMBER FUNCTIONS OF THE LIST CLASS:
FUNCTION TASK
Back()
Begin()
Clear()
Empty()
Pop_back()
Pop_front()
Push_back()
Push_front()
Gives reference to the last element
Gives reference to the first element
Deletes all the elements
Decides if the list is empty or not
Deletes the last element
Deletes the first element
Adds an element to the end
Addr an element to the front
Resize(),reverse(),size(),sort(),swap().unique()
EX:
#include<iostream.h>
#include<list>
#include<cstdlib>
Void display(list<int>&list)
{
List<int>::iterator p;
For(p=list begin();p!=lst.end();++p)
Cout<<*p<<,;
Cout<<\n\n;
}
Int main()
{
List<int>list1;
List<int>list2(5);
For(int i=0;i<3;i++)
List,push_back(rand()/100);
List<int>::iterator p;
For(p=list2.begin();p!=list2.end();++p)
*p=rand()/100;
Cout<<list,\n;
Display(list1);
Cout<<list2\n;
Display(list2);
//add two elements at the ends of list
List1.push_front(100);
List1.push_back(200);
//remove an element at the front of list2
List2.pop.front();
Count<<now list,\n;
Display(list1);
Cout<<now list2\n;
Display(list2);
List<int>listA,listB;
List A=list1;
List B=list2;
//merging two lists(un sorted)
List1.merge(list2);
Cout<<merged unsorted lists\n;
Disply(list1);
// sorting and merging
List A.sort();
List B.sort();
List A.merge(list B);
Cout<<merged sorted lists \n;
Display(list A);
//reversing a list
List A.reverse();
Cout<<reversed merged list \n;
Display(list A);
return 0;
}
MAPS:
A map is a sequence of(KEY,VALUE) pairs where a single value is associated with each
unique key as shown in diagram.
Key 1 Value 1
Key 2 Value2
Key 3 Value 3
Key N Value N
*retrieval of values is based om the key and it is very fast.we should specify the key to obtain
the associated value.
*a map is commonly called a associate array the key in specified using the subscript
operator[] as shown below
Phone[john]=111;
IMPORTENT MEMBER FUNCTIONS
Function Task
Begin()
Clear()
End()
Erase()
Insert()
Gives reference to the first element
Deletes all the elements from the map
Gives the reference to the end of the map
Deletes the specified element
Inserts elements are specified
UNIT -4 TEMPLATES
GENERIC FUNCTION
A generic function defines a general set of operations that will be
applied to various type of data
The type of dta that the function will operate upon is passed to it as parameter
A generic function created by using the keyword template.
It contain two types
1.function template
2.class template
FUNCTION TEMPLATE:
Function template that could be used to create a family with
differend argument types.
SYN:
Template<class T>
return type functionname(argument of types)
{
//.....
//body of function
}
EX:
#include<iostream.h>
Template<class T>
Void swap(T &x,T&y)
{
T temp=x;
X=y;
Y=temp;
}
Void fun(int m,int n,float a,float b)
{
Cout<<m and n before swap<<m<<<<n<<\n;
Swap(m,n);
Cout<<m and n after swap<<m<< <<n<<\n;
Cout<<a and b before swap<<a<< <<b<<\n;
Swap(a,b);
Cout<<a and b after swap<<a<< <<b<<\n;
}
Int main()
{
Fun(100,200,11,22,33,44);
return 0;
}
O//P:
m and n before swap:100 200
m and n after swap:200 100
a and b before swap:11.22 33.43
a and b after swap:33.43 11.22
BUBBLE SORT USING TEMPLATE FUNCTION:
#include<iostream.h>?
Template<class T>
Void bubble(T a[],int n)
{
For(int i=0;i<n-1;i++)
For(int j=n-1;i<j;j--)
If(a[j]<a[j-1])
{
Swap(a[j],a[j-1]);
}
}
Template<class x>
Void swap(x &a,x&b)
{
X temp=a;
A=b;
B=temp;
}
Int main()
{
Int X[5]={10,50,30,40,20};
Float y[5]={1.1,5.5,3.3,4.4,2.2}
Bubble(x,5);
Bubble(y,5);
Cout<<sworted x array;
For(int i=0;i<5;i++)
Cout<<x[i]<< ;
Cout<<endl;
Cout<<sorted y array;
For(int j=0;j<5;j++)
Cout<<y[j]<< ;
Cout<<endl;
return 0;
}
O/P:
Sorted x array: 10 20 30 40 50
Sorted y array:1.1 2.2 3.3 4.4 5.5
FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS:
A function templates contains more than one parameter is called multiple parameters.
SYN:
Template<class T,class T2,...>
Return type functionname(argument of types T1,T2)
- - - -
- - - -
- - - -
Body of function
- - - -
}
EX:
#include<iostream.h>
#include<string.h>
Template<class T1,class T2>
Void display(T1 x,T2 y)
Cout<<x<< <<y<<\n;
}
Int main()
Display(1999.EBG);
Display(12.34,1234);
return 0;
}
CLASS TEMPLATE:
Templates allow us to define generic classes using a templates with an
anonymous type
SYN:
Template<class T>
Class classname
{
//----
};
EX:
#include<iostream.h>
Const size=3;
Template<class T>
Class vector
{
T* V;
Public:
Vector()
{
V=new T[size];
For(int i=00;i<size;i++)
V[i]=0;
}
Vector(T*a)
{
For(int i=0;i<size;i++)
V[i]=a[i];
}
T operator *(vector & y)
{
T sum=0;
For(int i=0;i<size;i++)
Sum +=this->v[i]*y.v[i];
return sum;
}
};
Int main()
{
Int X[3]={1,2,3};
Int Y[3]={4,5,6};
Vector<int>V1;
Vector<int>V2;
V1=x;
V2=Y;
Int R=v1 *v2;
Cout<<R=<<R<<\n;
return 0;
}
O/P:
R=32
CLASS TEMPLATES WITH MULTIPLE PARAMETERS:
Syn
Template<class T1,class T2....>
Class classname
{
------
};
EX:
#include<iostream.h>
Template<class T1,class T2>
Class test
{
T1 a;
T2 b;
Public:
Test(T1 Z,T2 Y)
{
a=X;
b=Y;
}
Void show()
{
Cout<<a<<and<<b<<\n;
};
Int main()
Test<float,int>test1(1.23,123);
Test<int,char>test2(100,;w);
Text1.show();
Text 2.show();
return 0;
}
STL:
STL means standard template library ,it contains several components in given below
COMPONENTS OF STL:
The STL contains several components.
*containers
* algorithm
*iterators
The relationship between the there components in shown in diagram.

algorithm1 container iterator2 algorithm2
iterator1





iterator3
algorithm3

CONTAINERS:
A container in an object that actually stores data.it is a way data is organized in
memory
The STL container are implemented by template classes and therefore can be easily
customized to hold differend types of data.
Algorithm:
An algorithm is a procedures that is used to process the data contained in the
container
The STL algorithm reinfore the philosophy of reusability.
Advantage:
By using these algorithm programmers can save a lot of time and effort
STL algorithm,based on the nature of operation they perfore may be categorized as under:
1.retrieve (or) non-mutating algorithm
2.mututing algorithm
3.sorting algorithm
4.set algorithms
Relational algorithm
STL also contain a few numeric algorithm under the header file <numeric>
1.NON-MUTATING ALGORITHM:
OPERATION DESCRIPTION
1.adjacent-find()
2.count()
3.equal()
4.find()
Finds adjacent pairs of objects that are equal.
Counts of a value in a sequence
True if two ranges are the same
Finds first occurance of a value in a sequence
5.find-end()
6.search()
Finds last occurance of a value in a sequence
Finds a subsequence within a sequence
2.SORTING ALGORITHM
OPERATIONS DESCRIPTION
Binary-search()

Merge()
Pop-heap()
Upper-bound()
Lower-bound()
Conducts a binary search on an ordered
sequence
Merges two sorted sequences
Deletes the top element
Finds the last occurance of a specified value
Finds the first occurance of a specified value
3.MUTATING ALGORITHM
OPERATION DESCIPTION
Copy()
Fill()
Remove()
Reverse()
Reverse-copy()
Swap()
Copies a sequence
Fills a sequence with a specified value
Deletes elements of a specified value
Reverse the order of elements
Copies a sequence into reverse order
Swaps two elements
4.SET ALGORITHM
OPERATION DESCRIPTION
Includes()

Set.difference()

Set-intersection()

Set-union
Finds whether a sequence in a supseque of
another
Constructs a sequence that is the difference
of two ordered sets
Constructs a sequence that contains the
intersection of ordered sets
Produces ssorted union of two ordered sets
5.RELATIONAL ALGORITHM
OPERATIONS DESCRIPTION
Equal
Max()
Max-element()

Min()

Finds whether two sequences are the same
Gives maximum of two values
Finds the maximum element within a
sequence
Gives minimum of two values.
NUMERIC ALGORITHM:
OPERATIONS DESCRIPTION
Accumulated()

Inner-product()

Partial-sum
Accumulated the results of operation on a
sequence
Accumulates the results of operation on a
pair of sequence
Produces a sequence by operation on a pair
of sequence

FUNCTION:
A function object is a function that has been wrapped in a cqlass.so that it
looks like an object.
The class has only one member function,the overloaded() operator and no data
Function objects arte often used as arguments to certain containers and algorithm.
EX:
Sort(arry,arry+5,greater<int>());
FUNCTION OBJECT TYPE DESCRIPTION
Divides<T>
Equal to<T>
Logical-<T>
Minus<T>
Multiplies<T>
Arithmetic
Relational
Logical
Arithmetic
arithmetic
X/Y
X==Y
!X
X-Y
X*Y
EX:
#include<iostream.h>
#include<algotithm.h>
#include<functional>
Int main()
{
Int x[]={10,50,30,40,20}
Int y[]={70,90,60,80}
Sort(x,x+5,greater<int>());
Sort(y,y+4);
For(int i=0;i<5;i++)
Cout<<x[i]<< ;
Cout<<\n;
For(int j=0;j<4;j++)
Cout<<y[j]<< ;
Cout<<\n;
Int z[9];
Merge(x,x+5,y,y+4,z);
For(i=0;i<9;i++)
Cout<<z[i]<< ;
Cout<<\n;
return(0);
}
UNIT 5 INHERITANCE

Das könnte Ihnen auch gefallen