0% found this document useful (0 votes)
111 views243 pages

C++ Programming Essentials

The document describes the typical structure of procedural oriented programming (POP) and compares it with object oriented programming (OOP). In POP, the main program divides large programs into smaller functions that share global data. Functions transform data and pass it between each other. In contrast, OOP emphasizes data over procedures, divides programs into objects with their own data and functions, and allows objects to communicate through functions while hiding their internal data. The document then provides details on various OOP concepts like classes, objects, encapsulation, inheritance and polymorphism.

Uploaded by

Kiran Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views243 pages

C++ Programming Essentials

The document describes the typical structure of procedural oriented programming (POP) and compares it with object oriented programming (OOP). In POP, the main program divides large programs into smaller functions that share global data. Functions transform data and pass it between each other. In contrast, OOP emphasizes data over procedures, divides programs into objects with their own data and functions, and allows objects to communicate through functions while hiding their internal data. The document then provides details on various OOP concepts like classes, objects, encapsulation, inheritance and polymorphism.

Uploaded by

Kiran Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Typical Structure of POP Programs

Main Program

Function - 1 Function - 2 Function - 3

Function - 4 Function - 5

Function - 6 Function - 7 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 Derived type


Structure Array, Pointer
Built in type
Union, Class Reference
Enumeration Function

Floating type
Integer type
Float
Int Void
Double
char
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. ptr holds &a
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
a = 10
address of a 10 is stored.
Reference Variables
• A reference variable
provides an alias or
an alternative name
for an already existing total / sum
variable.
float total = 100;
float &sum = total;
Operators

Types of Operators

Unary Operators
Binary Operators Ternary Operators
One operand
Two operands 3 operands
e.g. -a
e.g. a+b 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 Explicit Casting


Automatic casting Manual casting
float f = 19.5; float f = 19.5;
int I = f; 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; Output :
void main() 30 10 20 10.
{ :: operator prints the global
int i =20; variable.
{
int i = 30;
cout<<i;
cout<<::i;
}
cout<<i;
cout<<::i;
}
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 Exit controlled


Loops Loops
e.g. for loop,while loop 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 Call by references
void swap (int * , int *); void swap (int & , int &);
void swap (int *p, int *q) void swap (int &ra, int &rb)
{ {
int temp; int temp;
temp = *p; temp = ra;
*p = *q; ra = rb;
*q = temp; rb = temp;
} }
swap (&a,&b); //calling 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 Data
Access
Functions
From outside

Public area
Access Data

From outside Functions


allowed
Classes
Class declaration and class function definition -
Class item
{
private:
int number;
int cost;
public :
getdata( int,int );
putdata( );
};
void getdata( int c,int no) //definition
{ cost = c; number = no;}
void putdata(int ) //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 :
[Link]-name();
Creating objects
void main()
{
item earPhones;
[Link] = 10; //error
[Link] = 1000; //error
[Link](10,1000); // function call
[Link](); // 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 Here 16 bytes of data is
{ allocated .
int cost, avg; 8 bytes for object city and 8
float speed; bytes for object accord.
public: cost
..functions.. city avg
speed
};
void main()
cost
{ accord avg
test city, accord; 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; //declaration
};
int test :: x; //definition
Static Member Functions
Members which are declared as class test
static have the following {
properties- int x,y,z;
static int count;
• Can access only static
members variables. public:
static void func()
{
• Can be called using the class
name. count++;
x++; //error
}
};
Void main()
{ test func(); // call
}
Arrays of Objects
class test
{ count
int x,y,z;
static int count;
t[0] x,y,z
public:
functions..
}; t[1] x,y,z
Void main()
{
t[2] x,y,z
test t[3];
}
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 void xyz :: xyz(int x)
- takes arguments. {
- is called automatically when a = x;
an object is created. }
class xyz
{ void main()
int a; {
public: xyz obj1(5); //implicit
int(); call to
xyz(int); parameterized
}; constructor
void xyz :: xyz() { a = 0;} xyz obj2 = xyz(10);
//explicit call
}
Copy Constructor
Copy constructor void xyz :: xyz(xyz &temp)
- used to copy an object to {
another a = temp.a;
- takes reference of its type as }
an argument
class xyz void main()
{ {
int a; xyz obj1
public: xyz obj2(obj1);
xyz(); xyz obj3 = xyz(obj1);
xyz(int); //explicit call
xyz(xyz &); // declaration }
};
void xyz :: xyz() { a = 0;}
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 int main()
{ public: {
alpha(){ alpha A1,A2,A3,A4;
count++; { alpha A5; }
cout<<count; {alpha A6; }
~alpha(){ }
cout<<count; Output:
count--; 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 1

Class 2 Class 2 Class 3 Class 4

Simple Inheritance 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; private : a
public : public : b
int b;
}; Class B

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

class D : private B
{ private : x,b
int x; public : func()
public:
func();
Class D
};
Single Inheritance - protected
class B{
int a; private : a
protected: int y; protected : y
public : b
public :
int b; Class B
};
class D : protected B
private : x
{ protected : b , y
int x; public : func()
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{ void main()
public: display(); {
}; D obj;
class B2{ [Link](); // error
public: display(); obj.B1::display();
}; obj.B2::display();
class D : public B1,public }
B2
{ .. };
Hybrid Inheritance
class Parent class grandchild : public
{ public : child1,public child2
calc(); {…}
}; void main()
class child1 : public {
virtual Parent {..}; grandchild gc;
class child2 : virtual [Link]();
public Parent{ .. }; }
Inheritance with Default
Constructors
class base{ void main()
int a; {
public: derived d;
base(){ }
cout<<“Base Class!!”} Output :
} Base Class
class derived : public base{ derived Class
int b; -Base class constructor is
public: called first and then
derived(){ derived class constructor
is called.
cout<<“derived Class!!”} -Default constructor is
} implicitly called.
Inheritance with Parameterized
Constructors
class base{ void main()
int a; {
public: base(){} derived d(5,10);
base(int aa){ a = aa; }
cout<< “a = ”<<a; } Output :
} a=5
class derived : public base{ b = 10
int b; - Base class parameterized
public: derived(){} constructor is called first and
derived( int aa, int bb) : base(aa) then derived class constructor
is called.
{ b = bb ; -Parameterized constructor of the
cout<< “a = ”<<a; } base class has to be explicitly
} called from the derived class
Parameterized constructor
Composition vs Inheritance
• Having an object of a • Object of one class
class as a member of obtaining the properties
another class is called of an object of another
composition. class is called
• An object of wheel class inheritance.
will be a member of the • Suppose car class
car class. inherits from vehicle
• we can say that car has a class.
wheel. • Then we can say that “car
• Composition exhibits has- is a vehicle.
a relationship. • Inheritance exhibits is-a
relationship.
Composition Syntax
class X void ass(int aa)
{ int a; { a = aa ;}
public: void get()
void ass(int aa) { return a ;}
{ a = aa ;} };
void get() void main()
{ return a ;} {
}; Y y;
Class Y [Link](10);
{ int a; [Link](20);
public: [Link]();
X x; [Link]();
}
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 main()
{ int a,b; {
public: sample x;
void setvalue() [Link]();
{ a = 25;b = 50; friend cout<<“mean value :
float mean(sample s); ”<<mean(x);
};
float mean(sample s) return 0;
{ }
return((s.a + s.b)/2);
}
A global function declared friend of
two classes
class ABC; // forward declaration class ABC
Class XYZ { int a;
{ int x; public:
public: void setvalue(int i){ a = i;}
void setvalue(int i) friend void max(XYZ,ABC);
{ x = i;} };
friend void max(XYZ,ABC); int main()
}; {
void max(XYZ m,ABC n) ABC abc;
{ [Link](10);
if(m.x > n.a ) cout<< m.x; XYZ xyz;
else cout<< m.x; [Link](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 With the keyword
function as inline. “inline”
• Define the function Class abc{
inside the class. public:
class abc{ void func();
public : };
void func(){ ..} inline void func()
// inline function {
}; }
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

Run time
Compile time
polymorphism
polymorphism

Function Operator Virtual


Overloading Overloading 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) void main()
{ {
return (r*r*r); int cube , cylinder,
} cuboid;
int vol(int r,int h) cube = vol(5);
{ cylinder = vol(5,3);
return(3.14*r*r*h); cuboid = vol(6,7,4);
} }
int vol(int l,int b,int h) Here there are 3 functions
{ with the same name but
return (l*b*h); different number of
} arguments.
Constructor Overloading
Here there are three functions – void xyz :: xyz(xyz &temp)
constructors with the same name {
but different arguments. This is a = temp.a;
called constructor overloading. }
class xyz
void main()
{
{
int a; xyz obj1
public: xyz obj2(obj1);
xyz(); xyz obj3 = xyz(obj1);
xyz(int); //explicit call
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 Binary
operators operators

Member Friend Member Friend


function function function function

No One One Two


argument argument argument argument
Overloading unary operators using
member functions
class space void main()
{ {
int x,y,z; space s;
public : [Link](3,-6,9);
void get(int a,int b,int c) [Link]();
{ x = a; y = b; z = c;} -s;
void display(){..} [Link]();
void operator-(); }
}; Output:
void space :: opertor-() X = 3, y = -6; z = 9
{ x = -x; y = -y; z = -z;} 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 void main()
{ {
int x,y,z; space s;
public : [Link](3,-6,9);
void get(int a,int b,int c) [Link]();
{ x = a; y = b; z = c;} -s;
void display(){..} [Link]();
friend void operator-(space&); }
}; Output:
void operator-(space &s) X = 3, y = -6; z = 9
{ s.x = -s.x; s.y = -s.y; X = -3, y = 6; z = -9
s.z = -s.z;}
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;
[Link] = real + [Link];
[Link] = imag + [Link];
return temp;
}
void main()
{ complex c1,c2,c3;
c3 = c1 + c2; //c3 = [Link]+(c2);
[Link]();
}
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;
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return temp;
}
void main()
{ complex c1,c2,c3;
c3 = c1 + c2; // c3 = operator+(c1,c2);
[Link]();
}
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 void main()
is achieved using {
Pointers item it;
class item item *p;
{ p = &it;
int code , price ; int code,price;
public : cout<<“Enter code and price:”;
void getdata(int c, int p) cin>>code>>price;
{code = c; price = p;} p->getdata();
void display() p->display();
{cout << “code : ”<<code; }
cout<< “price : “<<price;}
};
Pointer to array of objects
void main() p = it;
{ for(int i=0;i<3;i++)
item it[3]; {
item *p; p->display();
p = it; p++;
int code,price; }
for(int i=0;i<3;i++) }
{
cout<<“Enter code and price:”; Here we are using pointer to array
cin>>code>>price; of objects.
p->getdata(code,price); When we use pointers to access
p++; class members -> operator is
used instead of the .(dot )
} operator.
Array of Pointer to objects
void main() for( int i=0 ; i<=n; i++)
{ {
item it; p[i] -> display();
item *p[5]; }
int code, price ,option , i=0; return;
do }
{
p[i] = new item;
cout<<“Enter code and price”; Here array of pointers of the type
cin>>code>>price; class are used to access objects.
p[i]->getdata ( code, price);
i++;
}while(i<10);
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 void display()
{ {
char name[20]; cout<<“Name : ”<<name;
float age; cout<<“Age : ”<<age;
public: }
person( char *s , float a) };
{ strcpy ( name , s); void main()
age = a; } {
person & person :: greater( person person p1(“John” , 37.50 ) ;
&x) person p2(“Ahmed” , 29.50 ) ;
{ person p3(“Hebber” , 40.25 ) ;
if( [Link] >= age)
return x; person p = [Link](p3);
else [Link]();
return *this
} }
Pointers to Derived Objects
class BC void main()
{ {
public: int b; BC *bptr , base;
void show() bptr = &base;
{cout<<“b =”<<b <<“\n”;} bptr->b = 100;
}; bptr->show();
class DC : public BC
{ DC derived;
public: int d; bptr = &derived;
void show() bptr->b = 200;
{cout<<“b =”<<b <<“\n”; bptr->d = 300; //wont work
cout<<“d =”<<d <<“\n”;} 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 void main()
{ {
public: int b; BC *bptr , base;
virtual void show() bptr = &base;
{cout<<“b =”<<b <<“\n”;} bptr->b = 100;
}; bptr->show();
class DC : public BC
{ DC derived;
public: int d; bptr = &derived;
void show() bptr->b = 200;
{cout<<“b =”<<b <<“\n”; bptr->d = 300;
cout<<“d =”<<d <<“\n”;} 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 void main()
{ {
int *v,size; int x[3] = {1,2,3};
public : int y[3] = {4,5,6};
vector(int m) vector v1(3);
{v = new int[size = m]; vector v2(3);
for(int I = 0; i<size ; i++) v1 = x;
v[i] = 0; } v2 = y;
vector(int *a)
{ for(int i = 0; i<size ; i++) }
v[i] = a[i] ; } 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> void main()
class vector {
{ int x[3] = {1,2,3};
T *v,size; int y[3] = {4,5,6};
public : vector <int> v1;
vector(int m) vector <int> v2;
{v = new T[size = m]; v1 = x;
for(int I = 0; i<size ; i++) v2 = y;
v[i] = 0; } }
vector( T *a)
{ for(int i = 0; i<size ; i++)
v[i] = a[i] ; }
};
Templates
Template<class T> void main()
class vector {
{ int x[3] = {1,2,3};
T *v,size; int y[3] = {4,5,6};
public : vector <float> v1;
vector(int m) vector <float> v2;
{v = new T[size = m]; v1 = x;
for(int I = 0; i<size ; i++) v2 = y;
v[i] = 0; } }
vector( T *a)
{ for(int i = 0; i<size ; i++)
v[i] = a[i] ; }
};
Two Generic Data Types in a Class
Definition
template<class t1,class t2> int main()
class test {
{ test <float,int> test1(1.23,123);
t1 a; test <int , char>test2(1.23,123);
t2 b;
public:
test(t1 x, t2 y) [Link]();
{ a = x; b = y;} [Link]();
void show()
{ cout<<“a = ”<<a<<“b = ”<<b;} 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> Output :
void display(t x) Explicit display
{ Template display
cout<<“template display”; Template display
}
void display (int x)
{
cout<<“Explicit display”;
}
int main()
{
display(100);
display(12.34);
display(‘C’);
}
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
[Link] 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
{
…. //block of statements which detects
throw exception; // and throws an exception
….
}
catch(type arg) //catches an exception
{
….. //block of statements that handles
} // the exception
Exceptions Handling Mechanism
int main() else
{ throw x;
int a,b; }
cout<<“Enter 2 values”; catch(int i)
cin>>a; cout<<“exception
cin>>b; caught”<<“x = 0”;
int x = a-b;
try cout<<“END”;
{ return 0;
if(x!=0) }
cout<<a/x;
Function Invoked by try block
throwing exception
Throw point
Function that
Invoke
Throw causes an
function
Exception Exception

Try block
Invokes a function
that contains an
Exception

Catch block
Catches and handles
the exception
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
Exceptions-
catch(…)
{
…. //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 Read data Program File
To files from flies interaction
Program + Data

Write data Console program


Get data from On interaction
the keyboard Console Unit output screen
Screen and Keyboard

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


Input Stream

Disk Files Program

Output Stream Data Output


Write Data

File Input and Output Streams


Stream Classes for file Operations
ios iostream file

istream streambuf 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 steps-
1. 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() //reading from the same file
{ ifstream inf(“ITEM”);
ofstream outf(”ITEM”); inf>>name;
// writing into file “ITEM” [Link]();
cout<<“Enter Name:”; //writing the read name on
char name[20]; // the output screen.
cin>>name; cout<<“Name : ”<<name;
outf<<name; }
[Link]();
Working with Multiple File using
open() function.
int main() char str[20];
{ ifstream inf1 , inf 2;
ofstream outf; [Link](“Country”);
[Link](”country”); [Link](“Capital”);
// writing into file “Country” while(inf1)
outf<<“USA”; { inf1>>str;
outf<<“United Kingdom”; cout<<str;
[Link](); }
// writing into file “Capital” while(inf2)
[Link](”Capital”); { inf2>>str;
outf<<“Washington”; cout<<str;
outf<<“London”; }
[Link](); [Link]();
[Link]();
}
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 Action
[Link](0,ios::beg) go to start
[Link](0,ios::cur) stay at the current
location.
[Link](m,ios::beg) move to (m+1)th
byte from the beg.
[Link](-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. Syntax-
[Link]((char*)&V , sizeof(V));
[Link]((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 void student::read()
{ {
int rno; cout<<“Enter roll no:”;
char name[20]; cin>>rno;
public: cout<<“Enter name :”;
void read(); cin>>name;
void display(); }
}; void student::display()
{
cout<<“RollNo : ”<<rno;
cout<<“Name : ”<<name;
}
Reading and Writing Class Objects
void main() [Link]();
{
student s[3]; ifstream inf;
ofstream outf; [Link](“students”);
[Link](“students”);
cout<<“Enter details for 3 for(int i=0;i<3;i++)
students : ”; {
for(int i=0;i<3;i++) [Link]((char*)&s[i], sizeof(s[i]));
{ s[i].display()
s[i].read(); }
[Link]((char*)&s[i], sizeof(s[i])); [Link]();
} }
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.
2. fail() returns true if an input or an
output operation has failed.
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; else
[Link](“ABC”); {
while(![Link]()) if([Link]())
{ {
… //report fatal error
//process the file. }
} else
if([Link]()) {
{ [Link]();
//terminate program }
//normally }
} 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 Associative Derived


Containers Containers Containers

•Vector •Set map •Stack


•Deque •Multiset •Queue
•List •Map •Priority queue
•Multimap
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 I/D in I/D at end
access middle

Vector fast slow fast at back


List slow fast fast at front
Deque fast slow fast at both
ends
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
[Link] 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
[Link] 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
[Link] 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
[Link] 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
[Link] method – random
2. Direction of movement – forward and
backward
3. I/O capability – read/write
4. Remark – can be saved
Data Structure
• A data structure is a data object together
with the relationships that exists among
the instances and the individual elements
that compose an instance. These
relationships are provided by specifying
the functions of interest.
• It concerns representation of data objects
as well as the implementation of the
functions of interest for the data objects.
Linear List
• A linear list is a data object whose
instances are of the form (e1,e2,e3,….,en)
where n is a finite natural number.
• The e1 terms are the elements of the list
and n is its length.
• The elements may be viewed as atomic
because their individual structure is not
relevant to the structure of the list.
Linear List
• When n = 0 the list is empty.
• When n>0 , e1 is the first element and en
the last.
• e1 comes before e2 , e2 comes before e3
and so on.
Linear List
Some examples of linear lists are : -
• An alphabetized list of students in a class.
• A list of exam scores in a non decreasing
order.
• A list of gold medal winners in Olympics.
• An alphabetized list of members of
Congress.
Linear List
The following operations can be performed
on linear list –
• Create a linear list.
• Determine whether the list is empty.
• Determine the length of the list.
• Find the k th element.
• Search for a given element.
• Delete the k th element.
• Insert a new element after k th element.
Linear List
• Linear List may be specified as an abstract
data type (ADT) in which we provide a
specification of the instances as well as of
the operations that are to be performed .
• The abstract data type specification is
independent of any representation.
• All representations of the ADT must satisfy
the specification.
Linear List
template<class T>
class LinearList
{
private:
int length,MaxSize;
T *element;
public:
LinearList(int MaxListSize = 10);
~LinearList(){ delete [] element;}
bool IsEmpty() const {return length == 0;}
int Length() const { return length ; }
bool find(int k, T& x) const;
int Search(const T &x);
LinearList <T>& Insert(int k, T &x);
LinearList <T>& Delete(int k, const T &x);
void output(ostream & out) const;
};
Linear List
Constructor for creating a linear list
template<class T>
LinearList<T> :: LinearList(int MaxListSize)
{
MaxSize = MaxListSize;
element = new T[MaxSize];
length = 0;
}
Linear List
Set x as the k th element of the list.
Return false if no k th element in the list.
template<class T>
Bool LinearList<T> :: find(int k, T& x) const
{
if(k<1 || k>Length)
return false;
else
x = element[k-1];
return true;
}
Linear List
Locate x and return the position of x if found.
If it is not found return 0.
template<class T>
int LinearList<T> :: Search(const T &x)
{
for( int i=0;i<Length ;i++)
if( element[i] == x)
return ++x;
return 0;
}
Linear List
//set x as the k th element and delete it
template<class T>
LinearList <T>& LinearList <T> ::Delete(int k, T &x)
{
if(Find(k,x))
{
for( int i = k; i<length ; i++)
element[i-1] = element[i];
length--;
return *this;
}
else
throw OutOfBounds();
}
Linear List
Insert x after the k th element
Throw OutOfBound exception if no k th element
Throw NoMem exception if list is already full.
template<class T>
LinearList <T>& LinearList <T> ::Insert(int k, const T &x)
{
if(k<0 || k>Length) throw OutOfBounds();
if(Length == MaxSize) throw NoMem();
for( int i = length-1; i>=k ; i--)
element[i+1] = element[i];

element[k] = x;
length++;
return *this;
}
Linear List
Display the list on the screen
template<class T>
void LinearList <T> ::output(ostream &
out)const
{
for(int i = 0;i<Length ; i++)
out<<element[i]<<“ ”;
}
Linear List
#include<iostream.h>
#include<llist.h>
#include<xcept.h>
void main()
{
try
{
LinearList<int> L(5);
cout<<“Length = ”<<[Link]()<<endl;
cout<<“IsEmpty = ”<<[Link]()<<endl;
[Link](0,2).Insert(1,6);
cout<<“List is : ”<<[Link](cout);
int z;
[Link](1,z);
Linear List
(contd..)
cout<<“The first element is : “<<z<<endl;
cout<<“Length = ”<<[Link]()<<endl;
cout<<“IsEmpty = ”<<[Link]()<<endl;
[Link](1,z);
cout<<“Deleted element is ”<<z<<endl;
cout<<“List is : ”<<[Link](cout);
}
catch(..)
{
cerr<<“An exception has occured”<<endl;
}
}
Linear List
Linear Linked List
template class<T>
class ChainNode {
private:
T data;
ChainNode<T> *link;
public:
friend Chain<T>;
};
Linear List
Linear Linked List
template class<T>
class Chain{
private:
ChainNode<T> *first;
public:
Chain(){first = 0;}
~ Chain();
bool IsEmpty()const{return first == 0;}
int Length()const;
bool Find(int k, T&x);
int Search(const T&x) const;
Chain<T>& Delete(int k, T&x);
Chain<T>& Insert(int k, const T&x);
void Output(satream& out) const;
}
Linear List
Chain destructor.
Delete all nodes in chain.
template class<T> first next
Chain<T>::~Chain()
{
ChainNode<T> *next;
while(first)
{
next = first->link;
next
delete first; first
first = next;
}
}
Linear List
Returns the no of elements in the chain.
template class<T>
int Chain<T>::Length() const
{
ChainNode<T> *current = first;
int len = 0;
while(current)
{
len++;
current = current->link;
}
return len;
}
Linear List
Set x to the kth element in the chain
Return false if no kth return true otherwise.
template class<T>;
bool Chain<T> :: Find(int k, T&x) const
{
if (k < 1) return false;
ChainNode<T> *current = first;
int index = 1;
while(index < k && current){
current = current->link;
index++; }
if(current){ x = current - >data; return true;}
return false;
}
Linear List
Locate x . Return the position of x.
Return 0 if not found.
template class<T>;
bool Chain<T> :: Search(const T&x) const
{
ChainNode<T> *current = first;
int index = 1;
while(current ->data != x && current){
current = current->link;
index++; }
if(current)
return index;
return 0;
}
Linear List
Insert the chain of elements onto the output
screen.
template class<T>;
void Chain<T> :: Output(ostream &out) const
{
ChainNode<T> *current;
for(current = first;current;current = current->link)
out<<current->data<<“ ”;
}
Linear List
Set x to the kth element and delete it.
Throw OutOfBounds() exception if no kth ele.
template class<T>
Chain<T> Chain<T>::Delete(int k,T&x){
if(k<1 || !first) throw OutOfBounds();
ChainNode<T> *p = first;
if(k == 1)
first = first->link;
else{
ChainNode<T> *q = first;
for(int index =1;index<k-1 &&q;index++)
q = q->link;
q->link = p->link; //remove from chain
x = p->data;
delete p;
return *this;
}
Linear List
Insert x after k th element.
Throw OutOfBounds() exception if no kth ele.
Throw NoMem() exception if inadequate memory.
template class<T>
Chain<T>& Chain<T>::Insert(int k,T&x){
if(k<0) throw OutOfBounds();
ChainNode<T> *p = first;
if(k == 1)
first = first->link;
else{
ChainNode<T> *q = first;
for(int index =1;index<k-1 &&q;index++)
q = q->link;
q->link = p->link; //remove from chain
x = p->data;
delete p;
return *this;
}
Trees
• Linear data structures are not suitable for
representation of hierarchical data.
• In hierarchical data we have an ancestor-
descendant, superior-subordinate ,whole-
part or similar relationship among data.
Trees

Joe

Ann Mary John

Mark Sue Chris

Descendants of Joe
Trees

Federal Government

Education Defense Revenue

Air Force Army Navy

Modules of Federal government


Trees
• A tree t is a finite nonempty set of
elements.
• One of these elements is called a root and
the remaining elements (if any) are
partitioned into trees which are called the
subtrees of t.
Trees
• Children – the edges in a tree connect an
element node and its children nodes. For
example air force , navy and army are children
of defense.
• Parent – defense is the parent of air force , navy
and army .
• The extension of this terminology to include the
terms grandchild , grandparent , ancestor and
descendant.
• Elements with no children are called leaves.
Trees
• Level – the tree root is at level1 ,its
children are at level2, their children are at
level3 and so on.
• The degree of an element is the number of
children it has .
• The degree of a leaf is zero.
• The degree of a tree is the maximum of its
element degrees.
Binary Trees
A binary tree is a finite collection of elements. When the
binary tree is not empty , it has a root element and the
remaining elements (if any) are partitioned into two
binary trees which are called the left and right subtrees
of t.
The essential differences between a binary tree and a tree
are –
1. The binary tree can be empty whereas a tree cannot.
2. Each element in a binary tree has exactly two
subtrees . Each element in a tree can have any number
of subtrees.
3. The subtrees of each element in a binary tree are
ordered. That is we distinguish between the left and
right subtrees. The subtrees in a tree are unordered.
Properties of Binary Trees
Property1 - The drawing of every binary tree
with n elements has exactly n-1 edges.
Proof :
Every element in a binary tree has
exactly one parent. There is exactly one
edge between every child and parent. So
no of edges is n-1.
Binary Trees
• The height or depth of
a binary tree is the
Joe number of levels in it.
• This binary tree has
Mary height 4.
Ann

Mark Sue

George
Properties of Binary Trees
Property 2 – A binary tree of height h has at
least h and at the most 2^h -1 elements in
it.
Suppose the height of a binary tree is 4.
Then the minimum no of elements it would
have is 4.
The maximum no of elements it would have
is 2^4 – 1.
Properties of Binary Trees

A
A

B
B C

C
D E F G

Here height is 3. Here the height of the tree is 3.


The minimum no of elements is 3 The maximum no of elements is
2^3 -1 = 7
Properties of Binary Trees
Property 3 – the height of a binary tree that
contains n elements is at most n and at least
log2(n+1).
Suppose the no of elements are 3.
Then the maximum height is n that is 3.
The minimum height is log2(n+1) that is log2(3 +
1)
= log2(4)
= 2log2(2)
= 2(1)
= 2
Properties of Binary Trees

A
A

B
B C

Here no of elements is 3 Here no of elements is 3


The maximum no of levels is 3 The minimum no of levels is
2
Binary Trees
• Full Binary Tree – A binary tree of height h
that contains exactly 2^h -1 elements is
called full Binary Tree.
1

2 3

4 5 6 7
Complete Binary Tree
The following are 1

complete binary trees.


2 3

4 5 6
1

2 3
1

4 5
2
Properties of Binary Trees
Property 4 :
Let i , 1<=i<=n , be the number assigned to
an element of a complete binary tree.
1. If I = 1, then this element is the root of the binary tree.
If i>1, then the parent of this element has been
assigned the number[i/2].
2. If 2i>n, then this element has no left child. Otherwise ,
its left child has been assigned the number 2i.
3. If 2i+1>n, then this element has no right child.
Otherwise , its right child has been assigned the
number 2i+1.
Formula Based Representation

A A

B C B C

D E F G D E F G

A B C A B C D E
Formula Based Representation
Disadvantages –
To represent a right skewed binary tree
through arrays , a lot of memory space is
wasted.
Binary Tree
template<class T>
Class BinaryTreeNode
{
private:
T data;
BinaryTreeNode<T> *leftc ,*rchild;
public:
BinaryTreeNode() {leftc = rchild = 0;}
BinaryTreeNode(const T& e )
{data = e; leftc = rchild = 0;}
BinaryTreeNode(const T& e , BinaryTreeNode*1,
BinaryTreeNode *r)
{ data = e;
leftc = 1;
rchild = r;
}
}

You might also like