Professional Documents
Culture Documents
Main Program
Function - 1
Function - 2
Function - 4
Function - 6
Function - 7
Function - 3
Function - 5
Function - 8
Global Data
Function - 1
Function - 2
Function - 3
Local Data
Local Data
Local Data
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.
Data
Functions
Functions
Data
Functions
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.
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.
Built in type
Void
Derived type
Array, Pointer
Reference
Function
Floating type
Float
Double
Keywords
Fixed words having fixed meanings
Example : int , float , etc.
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.
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;
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;
Output :
30 10 20 10.
:: operator prints the global
variable.
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.
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);
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
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.
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.
Object-1
Object-2
Object-n
//declaration
//definition
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;
}
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;}
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.
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
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
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{ .. };
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.
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.
Composition Syntax
class X
{ int a;
public:
void ass(int aa)
{ a = aa ;}
void get()
{ return a ;}
};
Class Y
{ int a;
public:
X x;
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.
int main()
{
sample x;
x.setvalue();
cout<<mean value :
<<mean(x);
return 0;
}
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);
}
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
};
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;}
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
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
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
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 = ⁢
int code,price;
cout<<Enter code and price:;
cin>>code>>price;
p->getdata();
p->display();
}
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.
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();
}
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();
}
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();
}
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;
}
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);
}
Output :
Explicit display
Template display
Template display
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
//catches an exception
//block of statements that handles
// the exception
else
throw x;
}
catch(int i)
cout<<exception
caught<<x = 0;
cout<<END;
return 0;
}
Function that
causes an
Exception
Try block
Invokes a function
that contains an
Exception
Catch block
Catches and handles
the exception
Invoke
function
}
try
{
.
//invokes the function
}
catch(type arg) //catches an exception
{
..
// the exception
}
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 Stream
Disk Files
Write Data
Data Input
Program
Output Stream
Data Output
streambuf
iostream file
ostream
iostream
ifstream
fstream
ofstream
filebuf
fstream base
fstream file
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.
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();
}
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.
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
void student::read()
{
cout<<Enter roll no:;
cin>>rno;
cout<<Enter name :;
cin>>name;
}
void student::display()
{
cout<<RollNo : <<rno;
cout<<Name : <<name;
}
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();
}
1. eof()
2. fail()
else
{
if(infile.bad())
{
//report fatal error
}
else
{
infile.clear();
}
}
clear() resets the error state so
that further operations can be
attempted.
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