Date post: | 24-Feb-2018 |
Category: |
Documents |
Upload: | priya-raji |
View: | 224 times |
Download: | 0 times |
of 207
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
1/207
DEPARTMENT OF INFORMATION
TECHNOLOGY
CS6301 PROGRAMMING AND
DATASTRUCTURES II
LECTURE NOTES
1www.cseitquestions.in
UNIT I
OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
C++ Programming features - Data Abstraction - Encapsulation - class - object -
constructors static members constant members member functions pointers
references - Role of this pointerStorage classesfunction as arguments.
1.1 C++ PROGRAMMING FEATURES:
1.
The C++ programming language is based on the C language.
2. Although C++ is a descendant of the C language, the two languages are not always
compatible.
3. In C++, you can develop new data types that contain functional descriptions (member
functions) as well as data representations. These new data types are called classes.
4.
The work of developing such classes is known as data abstraction. You can work with
a combination of classes from established class libraries, develop your own classes, or
derive new classes from existing classes by adding data descriptions and functions.
5.
New classes can contain (inherit) properties from one or more classes. The classes
describe the data types and functions available, but they can hide (encapsulate) the
implementation details from the client programs.
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
2/207
6. You can define a series of functions with different argument types that all use the
same function name. This is called function overloading. A function can have the
same name and argument types in base and derived classes.
7. Declaring a class member function in a base class allows you to override its
implementation in a derived class. If you use virtual functions, class-dependent
behavior may be determined at run time. This ability to select functions at run time,
depending on data types, is called polymorphism.
8. You can redefine the meaning of the basic language operators so that they can
perform operations on user-defined classes (new data types), in addition to operations
on system-defined data types, such as int, char, and float. Adding properties to
operators for new data types is called operator overloading.
9. The C++ language provides templates and several keywords not found in the C
language. Other features include try-catch-throw exception handling, stricter type
checking and more versatile access to data and functions compared to the C language.
2www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
3/207
1.2 DATA ABSTRACTION:
Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in
program without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation
of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs,
and DVD players, BUT you do not know its internal details, that is, you do not know
how it receives signals over the air or through a cable, how it translates them, and
finally displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.
Now, if we talk in terms of C++ Programming, C++ classes provides great level of
data abstraction. They provide sufficient public methods to the outside world to play
with the functionality of the object and to manipulate object data, i.e., state without
actually knowing how class has been implemented internally.
In C++, we use classesto define our own abstract data types (ADT). You can use the
cout object of classostream to stream data to standard output like this:
#include
int main( )
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
4/207
Access Labels Enforce Abstraction:
In C++, we use access labels to define the abstract interface to the class. A class may
contain zero or more access labels:
Members defined with a public label are accessible to all parts of the program. Thedata-abstraction view of a type is defined by its public members.
Members defined with a private label are not accessible to code that uses the class.
The private sections hide the implementation from code that uses the type.
There are no restrictions on how often an access label may appear. Each access label
specifies the access level of the succeeding member definitions. The specified access
level remains in effect until the next access label is encountered or the closing right
brace of the class body is seen.
Benefits of Data Abstraction:
Data abstraction provides two important advantages:
Class internals are protected from inadvertent user-level errors, which might corrupt
the state of the object.
The class implementation may evolve over time in response to changing requirements
or bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author is
free to make changes in the data. If the implementation changes, only the class code
needs to be examined to see what affect the change may have. If data are public, then
any function that directly accesses the data members of the old representation might
be broken.
Data Abstraction Example:
Any C++ program where you implement a class with public and private members is
an example of data abstraction. Consider the following example:
#include
using namespace std;
class Adder
{
public:
4www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
5/207
//constructor
Adder(int i = 0)
{
total = i;
}
//
interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside
world int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
6/207
1.3 DATA ENCAPSULATION:
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstractionis a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected andpublic members. By default, all items defined in a class are
private.
For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved.
To make parts of a class public(i.e., accessible to other parts of your program), you
must declare them after the publickeyword. All variables or functions defined after
the public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all
other classes as possible.
6www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
7/207
Data Encapsulation Example:
Any C++ program where you implement a class with public and private members is an
example of data encapsulation and data abstraction. Consider the following example:
#include
#include
class Adder
{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside
world int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);a.addNum(30);
7www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
8/207
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
9/207
Syntax of a class
class class_name
{
Access Specifier:
Data Members
Access Specifier:
Function Members
};
Example:
Consider an example of class
class student
{
public:
int rollno,age; Data Members
char *name;
void getdetail()
{
Cin>>rollno>>age;
Cin>>name;
} Function Members
void printdetail()
{
Cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
10/207
Function Definition outside the Class
The function members which are declared inside the class can be defined outside of
the class using Scope Resolution Operator ::
Syntax for Defining the Function outside the Class:
Return Type class_name::function_name()
{
Function Body
}
Return type specifies the type of a function. Class name specifies the name of a classin which the function belongs. The operator:: denotes scope resolution operator. Function
name specifies the name of a function.
Example:
class student
{
public:
int rollno,age;
char *name; void
getdetail(); void
printdetail(); };
void student::getdetail()
{
Cin>>rollno>>age;
Cin>>name;
}
void student::printdetail()
{
Cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
11/207
1.5 OBJECTS:
Objects are the variables of user defined data type called class. Once a Class has been
created we can declare any number of variables belongs to that class. In the above example
class student we can declare any number of variables of class student in the main function.
Using objects we can access any public members of a class using Dot Operator.
For accessing Data Members and assigning value:
object_name.data_member=value;
For accessing Function Members:
Object_name.function_name();
Syntax:
Class_Name object1, object2, object3.object n;
void main ()
{ class Name
student s1, s2,s3; s1,s2,s3 are objects(variables) of class Student
s1.rollno=28; Object s1 assigns the value for the data member rollno=28
s1.getdetail (); Object s1 access (call) the function member getdetail () of student class
s1.printdetail (); Object s1 access (call) the function member
printdetail () of student class
}
Memory Requirement for Objects and Class:
Once the object is created memory is allocated for the data members of a class and not
for its function Members .So each object holds the total memory size of the data members.
For example in the class student the object s1 holds the memory size of 5 bytes. Char I byte,
int 2 bytes.
Once the class is created only single copy of function member is maintained which
is common for all the objects.
11www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
12/207
Class student
Function Members:
Void getdetail()
Void printdetail()
Object s1: Object s2: Object s3:
Data Member Name Data Member Name Data Member Name
Data Member Rollno Data Member Rollno Data Member Rollno
Data Member age Data Member age Data Member age
1.6 CONSTRUCTOR:
The main use of constructors is to initialize objects. The function of initialization is
automatically carried out by the use of a special member function called a constructor.
General Syntax of Constructor
A constructor is a special member function that takes the same name as the class
name. The default constructor for a class X has the form
X::X()
In the above example, the arguments are optional. The constructor is automatically
named when an object is created. A constructor is named whenever an object is defined or
dynamically allocated using the new operator.
There are several forms in which a constructor can take its shape namely:
Default Constructor:
This constructor has no arguments in it. The default Constructor is also called as the
no argument constructor.
For example:
class Exforsys
{
12www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
13/207
private:
int a,b;
public:
Exforsys();
...
};
Exforsys :: Exforsys()
{
a=0;
b=0;
}
Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor
can have parameters. This helps you to assign initial value to an object at the time of its
creation as shown in the following example:
#include
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including
constructor Line::Line( double len)
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
14/207
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the
program int main( )
{
Line line(10.0);
// get initially set length.
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
15/207
Exforsys e3=e2;
Both the above formats can be sued to invoke a copy constructor.
For Example:
#include
using namespace std;
class Exforsys
{
private:
int a;
public:
Exforsys()
{
}
Exforsys(int w)
{
a=w;
}
Exforsys(Exforsys& e)
{
a=e.a;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
16/207
Destructors
Destructors are also special member functions used in C++ programming language.
Destructors have the opposite function of a constructor. The main use of destructors is to
release dynamic allocated memory.
Destructors are used to free memory, release resources and to perform other clean up.
Destructors are automatically named when an object is destroyed. Like constructors,
destructors also take the same name as that of the class name.
General Syntax of Destructors
~ classname();
The above is the general syntax of a destructor. In the above, the symbol tilda ~
represents a destructor which precedes the name of the class.
Some important points about destructors:
Destructors take the same name as the class name.
Like the constructor, the destructor must also be defined in the public. The destructor
must be a public member.
The Destructor does not take any argument which means that destructors cannot be
overloaded.
No return type is specified for destructors.
For example:
class Exforsys
{
private:
...
public:
Exforsys()
{
}
~ Exforsys()
{
}
}
16www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
17/207
1.7 STATIC MEMBERS:
The Static Data Member of a class is like a global variable. Once it is defined the
static member will be initialized to zero. When the static member is declared inside the class
it should be defined outside of the class. Static Data Member of a class will be common to all
the objects which are declared in the class.
Syntax:
class stat
{
static int count; //static Data Member Declaration
}
int stat::count; //static Data member Defintion
Example Program:
#include
#include
class count
{
public:
static int countt;
void dispcount()
{
countt++;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
18/207
c4.dispcount();
c5.dispcount();
getch();
}
In this example class count has a static data member countt.This program is used for
counting the number of objects which is declared in the class.So when an object c1 access the
function dispcount() the static variable has the value 1.when s5 access the function the value
will be incremented to 5.
Output:
Object 1
Object 2
Object 3
Object 4
Object 5
NOTE:
Once the static data member is defined it is automatically initialized to zero.
1.8 CONSTANT MEMBERS:
Constant Objects and Constant Functions
Once the object is declared as constant it cannot be modified by any function.
Initially the value for the data members is set by constructor during the object
creation.
Constant objects can access only the constant member function .The constant function
is read only function it cannot alter the value of object data members
Syntax- Constant Function & Constant objects
class class_name{
class_name(parameters)
{
18www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
19/207
initialize the datamember with parameters;
}
return_type function_name() const //Constant member function
{
//read only function
}
};
void main()
{
const class_name object( parameter); //constant objects
object.function(); //constant objects access Constant member function
}
Ex:
void printdetails() const
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
20/207
Example program for constant function and constant objects
#include
#include
class time
{
public:
int hour,minute,second;
time(int temphr,int tempmin,int tempsec)
{
hour=temphr;
minute=tempmin;
second=tempsec;
}
void disp() const //constant member function
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
21/207
Output
Time is:8Hour: 55Minutes: 50Seconds:
5
50
40
Time is:8Hour: 55Minutes: 50Seconds:
In this example, the object of this time class is set with the default value of 8 hour 55
minutes and 50 seconds and it is initialized with constructor. Since this object t1 is a n
constant object it cannot be modified and it can access only the constant function in a class.
1.9 MEMBER FUNCTIONS:
1.9.1 Static Function
Static member functions have a class scope and they do not have access to the 'this'
pointer of the class. When a member is declared as static, a static member of class, it has only
one data for the entire class even though there are many objects created for the class. The
main usage of static function is when the programmer wants to have a function which isaccessible even when the class is not instantiated.
Syntax
class stat
{
static return_type function_name()
{
Statement;
}
};
Calling Static Function in the main Function
void main()
{
class_name::static function name();
}
21www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
22/207
Example:
#include
#include
class count
{
public:
static int
countt; count()
{
countt++;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
23/207
A non-static member function can be declared as virtual but care must be taken not to
declare a static member function as virtual. .
The programmer must first understand the concept of static data while learning the
context of static functions. It is possible to declare a data member of a class as staticirrespective of it being a public or a private type in class definition. If a data is
declared as static, then the static data is created and initialized only once. Non-static
data members are created again and again. For each separate object of the class, the
static data is created and initialized only once. As in the concept of static data, all
objects of the class in static functions share the variables. This applies to all objects of
the class.
A non-static member function can be called only after instantiating the class as anobject. This is not the case with static member functions. A static member function
can be called, even when a class is not instantiated.
A static member function cannot have access to the 'this' pointer of the class.
1.9.2 Inline member Function
We may either define a member function inside its class definition, or you may define
it outside if you have already declared (but not defined) the member function in the class
definition.
A member function that is defined inside its class member list is called an inline
member function. Member functions containing a few lines of code are usually declared
inline. In the above example, add() is an inline member function. If you define a member
function outside of its class definition, it must appear in a namespace scope enclosing the
class definition. You must also qualify the member function name using the scope resolution
(::) operator.
An equivalent way to declare an inline member function is to either declare it in the
class with the inline keyword (or define the function outside of its class) or to define it
outside of the class declaration using the inline keyword.
1.10 POINTERS:
Every storage location of memory has an associated address. The address is a number
that grows sequentially. For every program placed in memory, each variable or function in
the program has an associated address.
23www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
24/207
The address of operator:
The address of operator or Reference operator is denoted by the notation &. When the
user wants to get the address of a variable, then the reference operator & can be used. The
operator & is used to find the address associated with a variable.
The syntax of the reference operator is as follows:
&variablename - This means that the address of the variable name is achieved.
For Example
#include
using namespace std;
void main()
{
int exf=200;
int test=300;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
25/207
exforsys is an integer variable having the value of 100 stored in memory address location
3501.
When the variable exforsys is assigned to the variable test in the second statement:
test = exforsys;
The value of the variable exforsys 100 is copied to the variable test.
In the third statement, the address of the variable exforsys is denoted by reference operator
&exforsys is assigned to the variable x as:
x = &exforsys;
The address of the variable 3501 and not the contents of the variable exforsys is
copied into the variable x. The pointers concept fits in this statement. Pointers are the
variables that store the reference to another variable. Pointers are variables that store the
address of the variable that it is pointed by. Variable x is referred to as the pointer in the
above example.
The programmer must note that the address operator placed before a variable is not
the same as operator & placed after the variable. For example, &x is not same as x&.
Variable &x refers to address operator whereas x& refer to reference operator&. Pointer is a
variable that holds the address, also called pointer variable.
Defining Pointer Variables or Pointer:
To define pointer variable is as follows:
datatype_of_ variable_pointedto* pointer_varaible;
For example:
char* ch;
This defines that ch is a pointer variable which points to char data
type. int* i;
This defines that i is a pointer variable which points to int data
type. float* f;This defines that f is a pointer variable which points to float data type.
25www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
26/207
1.11 REFERENCES:
A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the reference name
may be used to refer to the variable.
C++ References vs Pointers:
1. References are often confused with pointers but three major differences between
references and pointers are:
2.
You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
3.
Once a reference is initialized to an object, it cannot be changed to refer to another
object. Pointers can be pointed to another object at any time.
4. A reference must be initialized when it is created. Pointers can be initialized at any
time.
Creating References in C++:
Think of a variable name as a label attached to the variable's location in memory. You
can then think of a reference as a second label attached to that memory location. Therefore,
you can access the contents of the variable through either the original variable name or the
reference.
For example, suppose we have the following example:
int i = 17;
We can declare reference variables for i as
follows. int& r = i;
Read the & in these declarations as reference. Thus, read the first declaration as "r is
an integer reference initialized to i" and read the second declaration as "s is a double
reference initialized to d.". Following example makes use of references on int and double:
#include
int main ()
{
// declare simple variablesint i;
26www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
27/207
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
28/207
/* calling a function to swap the values.*/
swap(a, b);
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
29/207
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
30/207
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
31/207
void exforsys( )
{
int x;
float y; //Automatic Variables
...
}
In the above function, the variable x and y are created only when the function
exforsys( ) is called. An automatic variable is created only when the function is called. When
the function exforsys( ) is called, the variables x and y are allocated memory automatically.
External:
External variables are also called global variables. External variables are defined
outside any function, memory is set aside once it has been declared and remains until the end
of the program. These variables are accessible by any function. This is mainly utilized when a
programmer wants to make use of a variable and access the variable among different function
calls.
Static:
The static automatic variables, as with local variables, are accessible only within the
function in which it is defined. Static automatic variables exist until the program ends in the
same manner as external variables. In order to maintain value between function calls, the
static variable takes its presence.
For example:
#include
using namespace std;
int exforsys(int);
int exforsys2(int);
void main( )
{
int in;
int out;
while(1){
31www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
32/207
cout >in;
if (in == 0)
break;
out=exforsys(in);
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
33/207
address. Function pointers can be used to simplify code by providing a simple way to select a
function to execute based on run-time values.
#include
int add(int first, int second)
{
return first + second;
}
int subtract(int first, int second)
{
return first - second;
}
int operation(int first, int second, int (*functocall)(int, int))
{
return (*functocall)(first, second);
}
void main()
{
int a, b;
int (*plus)(int, int) = add;
int (*minus)(int, int) = subtract;
a = operation(7, 5, plus);
b = operation(20, a, minus);
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
34/207
UNIT II
OBJECT ORIENTED PROGRAMMING CONCEPTS
String Handling Copy Constructor - Polymorphism compile time and run time
polymorphisms function overloading operators overloading dynamic memory
allocation - Nested classes - Inheritancevirtual functions.
2.1 STRING HANDLING:
C++ provides following two types of string representations:
The C-style character string.
The string class type introduced with Standard C++.
2.1.1 The C-Style Character String:
The C-style character string originated within the C language and continues to be
supported within C++. This string is actually a one-dimensional array of characters which is
terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above statement as
follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++:
34www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
35/207
Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
#include int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
36/207
{
char str1[10] = "Hello";
char str2[10] =
"World"; char str3[10];
int len ;
//
copy str1 into str3
strcpy( str3, str1);
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
37/207
str3 = str1;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
38/207
int a;
public:
Exforsys()
{ }
Exforsys(int w)
{
a=w;
}
Exforsys(Exforsys& e)
{
a=e.a;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
39/207
1. Function overloading
2. Operator overloading.
2.4 COMPILE TIME AND RUNTIMEPOLYMORPHISM: Compile time Polymorphism:
Compile time Polymorphism also known as method overloading.
Method overloading means having two or more methods with the same name
but with different signatures.
Run time Polymorphism:
Run time Polymorphism also known as method overriding.
Method overriding means having two or more methods with the same name,same signature but with different implementation.
Overloading is a form of polymorphism. In case of function overloading, the
information regarding which function is to be invoked corresponding to a function call is
available at compile time. This is referred to as static binding or compile time polymorphism,
as the object is bound with its function call at compile time.
Run time polymorphism is achieved through virtual functions. The function to be
invoked by the instance of a class is known during runtime. The functions are linked with the
class during runtime and not during compile time. When a base class pointer points to a sub
class instance, instead of invoking subclass function (a function having name similar to that
of function of a base class), it always invokes base class version. If the function in the base
class is defined as virtual, then it is known during runtime only, which version of the function
will be invoked, corresponding to a function call. Since the function is linked after
compilation process, it is termed as late binding or dynamic binding or run-time
polymorphism.
2.5 FUNCTION OVERLOADING:
It is also referred to as functional polymorphism. The same function can perform a
wide variety of tasks. The same function can handle different data types. When many
functions with the same name but different argument lists are defined, then the function to be
invoked corresponding to a function call is known during compile time.
39www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
40/207
When the source code is compiled, the functions to be invoked are bound to the
compiler during compile time, as to invoke which function depending upon the type and
number of arguments. Such a phenomenon is referred to early binding, static linking or
compile time polymorphism.
For example:
#include
//function prototype
int multiply(int num1, int num2);
float multiply(float num1, float num2);
void main()
{
//function call statements
int ans1=multiply(4,3);
//first prototype is invoked as arguments
//are of type int
float ans2 = multiply(2.5, 4.5); //second prototype is
invoked as arguments are of type float
}
The compiler checks for the correct function to be invoked by matching the type of
arguments and the number of arguments including the return type. The errors, if any, are
reported at compile time, hence referred to as compile time polymorphism.
2.6 OPERATOR OVERLOADING:
Operator overloading is a very important feature of Object Oriented Programming.
Curious to know why!!? It is because by using this facility programmer would be able to
create new definitions to existing operators. In other words a single operator can take up
several functions as desired by programmers depending on the argument taken by the
operator by using the operator overloading facility.
Broadly classifying operators are of two types namely:
Unary Operators Binary Operators
40www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
41/207
Unary Operators:
As the name implies, it operates on only one operand. Some unary operators are
named ++ also called the Increment operator, -- also called the Decrement Operator, ! , ~ are
called unary minus.
Binary Operators:
It operates on two operands. Some binary operators are arithmetic operators,
comparison operators, and arithmetic assignment operators.
2.6.1 Operator Overloading - Unary operators
Operator overloading helps the programmer to define a new functionality for the
existing operator. This is done by using the keyword operator.
The general syntax for defining an operator overloading is as follows:
return_type classname :: operator operator_symbol(argument)
{
.
Statements;
}
Operator overloading is defined as a member function by making use of the keyword
operator.
In the above: return_type - is the data type returned by the function
class name - is the name of the class
operator - is the keyword
operator symbol - is the symbol of the operator which is being overloaded or
defined for new functionality
:: - is the scope resolution operator which is used to use the function definition
outside the class. The usage of this is clearly defined in our earlier section of How
to define class members.
For example
Suppose we have a class say Exforsys and if the programmer wants to define a
operator overloading for unary operator say ++, the function is defined as,
41www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
42/207
Inside the class Exforsys the data type that is returned by the overloaded operator is
defined as,
class Exforsys
{
private:
..
public:
void operator ++();
.
};
The important steps involved in defining an operator overloading in case of unary
operators are:
Inside the class the operator overloaded member function is defined with the return
data type as member function or a friend function. The concept of friend function we will
define in later sections. If in this case of unary operator overloading if the function is a
member function then the number of arguments taken by the operator member function is
none as seen in the below example. In case if the function defined for the operator
overloading is a friend function which we will discuss in later section then it takes one
argument.
The operator overloading is defined as member function outside the class using the
scope resolution operator with the keyword operator.
#include
using namespace std;
42www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
43/207
class Exforsys
{
private:
int x;public:
Exforsys( ) { x=0; }//Constructor
void display();
void operator ++( );
};
void Exforsys :: display()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
44/207
In the above example we have created 2 objects e1 and e2 f class Exforsys. The
operator ++ is overloaded and the function is defined outside the class Exforsys.
When the program starts the constructor Exforsys of the class Exforsys initialize thevalues as zero and so when the values are displayed for the objects e1 and e2 it is displayed
as zero. When the object ++e1 and ++e2 is called the operator overloading function gets
applied and thus value of x gets incremented for each object separately. So now when the
values are displayed for objects e1 and e2 it is incremented once each and gets printed as one
for each object e1 and e2.
2.6.2 Operator Overloading - Binary Operators
Binary operators, when overloaded, are given new functionality. The function defined
for binary operator overloading, as with unary operator overloading, can be member function
or friend function.
The difference is in the number of arguments used by the function. In the case of
binary operator overloading, when the function is a member function then the number of
arguments used by the operator member function is one (see below example). When the
function defined for the binary operator overloading is a friend function, then it uses two
arguments.
Binary operator overloading, as in unary operator overloading, is performed using a
keyword operator.
Binary operator overloading example:
Sample Code
#include
using namespace std;
class Exforsys
{
private:
int x;
int y;
public:
44www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
45/207
Exforsys() //Constructor
{ x=0; y=0; }
void getvalue( ) //M ember Function for Inputti ng Val ues
{
cout > x;
cout > y;
}
void displayvalue( ) //M ember Function for Outputti ng Val ues
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
46/207
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
47/207
2.7 DYNAMIC MEMORY ALLOCATION:
Memory in C++ program is divided into two parts:
The stack: All variables declared inside the function will take up memory from
the stack.
The heap: This is unused memory of the program and can be used to allocate the
memory dynamically when program runs.
1. Many times, we are not aware in advance how much memory you will need to store
particular information in a defined variable and the size of required memory can be
determined at run time.
2.
We can allocate memory at run time within the heap for the variable of a given type
using a special operator in C++ which returns the address of the space allocated. This
operator is called newoperator.
If we are not in need of dynamically allocated memory anymore, you can use delete
operator, which de-allocates memory previously allocated by new operator.
The new and delete operators:
There is following generic syntax to use new operator to allocate memory
dynamically for any data-type.
new data-type;
Here, data-typecould be any built-in data type including an array or any user defined
data types include class or structure. Let us start with built-in data types. For example we can
define a pointer to type double and then request that the memory be allocated at execution
time.
We can do this using the newoperator with the following
statements: double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used
up. So it is good practice to check if new operator is returning NULL pointer and take
appropriate action as below:
double* pvalue = NULL;
47www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
48/207
if( !(pvalue = new double ))
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
49/207
However, the syntax to release the memory for multi-dimensional array will still
remain same as above:
delete [] pvalue; // Delete array pointed to by pvalue
Dynamic Memory Allocation for Objects:
Objects are no different from simple data types. For example, consider the following
code where we are going to use an array of objects to clarify the concept:
#include
class Box
{
public:
Box() {
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
50/207
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
2.8 NESTED CLASSES:
A class that contains the definition of another class called nesting class and the class
inside the nesting class called nested class.
The nesting class can access the data member and function member of a nested class.
Nested classes can directly use names, type names, names of static members, and
enumerators only from the enclosing class. To use names of other class members, you
must use pointers, references, or object names.
The nesting of classes enables building of powerful data structures.
Syntax
class Nesting_Class
{
Public:
Data Members of Nesting Class;
class Nested_Class
{
public:
Data Member of Nested Class
Function Members of Nested
Class }; };
void main()
{
Nesting_class::Nested_class Object;
object.Nested_class Datamember=value;
object.Nested_class Functionmember();}
50www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
51/207
Example:
#include
#include
class fxclg //Nesting Class
{
public:
class cse //Nested Class
{
public:
char name[10],dept[5];
int age;
void get()
{
coutname;
cin>>age;
cin>>dept;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
52/207
Output:
Enter Details Name Age Dept:
kumar
24
CSE
name kumar age: 24 dept: CSE
In this example, the class cse (nested class) is defined within the class fxclg(nesting
class),To declare the objects of a nested class we have to follow the procedure, fxclg::cse c1;
Using this object it access the data and function member of nested class cse
2.9 INHERITANCE:
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which makes it
easier to create and maintain an application. This also provides an opportunity to reuse the
code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and memberfunctions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the baseclass, and the new class is referred to as
the derivedclass.
The idea of inheritance implements the is arelationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.
Base & Derived Classes:
A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes. To define a derived class, we use a class derivation
list to specify the base class(es). A class derivation list names one or more base classes and
has the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected,or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then it is private by
default.
52www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
53/207
Type of Inheritance:
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hybrid Inheritance
Hierarchical Inheritance
2.9.1 Single Inheritance:
Example:
#include
#include
class student
{
public:
char name[10],collname[10],dept[5];
void getfun(){
coutname>>collname>>dept;
}
};
class cse:public student
{
public:
53www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
54/207
char sub1[5],sub2[5],sub3[5];
void getdet()
{
getfun();
coutsub1>>sub2>>sub3;
}
void putdet()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
55/207
2.9.2 Multiple Inheritance
A derived class with several base classes is called multiple inheritance.
Example:
#include
#include
class student
{
public:
char name[10],collname[10],dept[5];
void getfun(){
coutname>>collname>>dept;
}
};
class internal
{
public:
char sub1[5],sub2[5],sub3[5];
int im1,im2,im3;
void getdet()
{
coutsub1>>sub2>>sub3;
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
56/207
cin>>im1>>im2>>im3;
}
};
class cse:public internal,public student
{
public:
int ex1,ex2,ex3,t1,t2,t3;
void calc()
{
getfun();
getdet();
cout>ex1>>ex2>>ex3;
t1=ex1+im1;
t2=ex2+im2;
t3=ex3+im3;
}
void putdet()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
57/207
Output:
Enter name,college name,department
paul
fx
cse
Enter subject 1,2,3
maths
pds
dbms
Enter internal marks for subject1,2,3
50
50
50
Enter external marks for subject1,2,3
50
50
50
name paul collname fx dept cse
sub1 Total 100 sub2 100 sub3 100
2.9.3 Multilevel Inheritance
The mechanism of deriving a class from another derived class is known as multilevel
inheritance.
57www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
58/207
Example: STUDENT
TEST
RESULT
#include
#include
#include
class student
{
public:
char name[10],clgname[10];
int age,year;
void get()
{
cout>name>>clgname>>age>>year;
}
void put()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
59/207
{
coutm1>>m2>>m3;
}
void putmarks()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
60/207
r1.getmarks();
r1.getinternal();
r1.put();
r1.putmarks();
r1.finalmark();
getch();
}
In this example the student class is derived into test class and then the test class
further derived into result class. So the result class inherits the properties of both student and
test class.
2.9.4 Hierarchical Inheritance
Hierarchical Inheritance is a method of inheritance where one or more derived classes
are derived from common base class.
Example:
#include
class Side
{
public:
int l;
void set_values (int x)
{
l=x;
}
};
class Square: public Side
60www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
61/207
{
public:
int sq()
{
return (l *l);
}
};
class Cube:public Side
{
public:
int cub()
{
return (l *l*l);
}
};
int main ()
{
Square s;
s.set_values (10);
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
62/207
2.9.5 Hybrid Inheritance
Hybrid inheritance is combination of two or more inheritances such as single,
multiple, multilevel.
Example:
#include
class mm
{
protected:
int rollno;
public:
void get_num(int a)
{rollno = a;
}
void put_num()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
63/207
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
64/207
public:
void disp(void)
{
tot = sub1+sub2+e;put_num();
put_marks();
put_extra();
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
65/207
If a base class and derived class has same function and if you write code to access that
function using pointer of base class then, the function in the base class is executed even if, the
object of derived class is referenced with that pointer variable.
Example:
#include
class CPolygon
{
public:
int width, height;
void set_values (int a, int b)
{
width=a; height=b;
}
virtual int area ( )
{
Cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
66/207
};
void main ()
{
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout area( )
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
67/207
UNIT III
C++ PROGRAMMING ADVANCED FEATURES
Abstract class Exception handling - Standard libraries - Generic Programming -
templatesclass template - function templateSTLcontainersiteratorsfunction
adaptorsallocators -Parameterizing the class - File handling concepts.
3.1 ABSTRACT CLASS
The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used
to instantiate objects and serves only as an interface. Attempting to instantiate an object of anabstract class causes a compilation error. Thus, if a subclass of an ABC needs to be
instantiated, it has to implement each of the virtual functions, which means that it supports
the interface declared by the ABC. Failure to override a pure virtual function in a derived
class, then attempting to instantiate objects of that class, is a compilation error. Classes that
can be used to instantiate objects are called concrete classes.
3.2 EXCEPTION HANDLING
An exception is any unusual event, either erroneous or not, detectable by either
hardware or software, that may require special processing.
WITHOUT EXCEPTION HANDLING WITH EXCEPTION HANDLING
When an exception occurs, control goes to the Programs are allowed to trap
operating system, where typically exceptions.
an error message is displayed There is a possibility to fix the
the program is terminated problem and continuing execution
Exception handling mechanism
To detect and report error, The error handling code performs the following task
1.
Find the problem (H itthe exception)
2.Inform that an error has occurred. (Throwthe exception)
3.
Receive the error information. (Catchthe exception)
67www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
68/207
4. Take corrective actions. (Handlethe exception).
Keywords in Exception Handling
try
throw
catch
TRY BLOCK -The keywordtry is used to preface a block of statements
(surrounded by braces) which may generate exceptions.
->When an exception is detected, it is thrown using a throw statementin the try block.
CATCH BLOCK - defined by the keywordcatch catches theexceptionthrown
by the throw statement in the try block, and handles it appropriately.
Exception Handling Syntax:
try //try block
{
.
throw exception; // Block of statements which detects and throws an exception
68www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
69/207
}
catch(type arg) // Catches exception
{
.
.. // Block of statements that handles the exception
}
Example:
#include
int main()
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
70/207
In C++ only synchronous exception can be handled.
Factors determining Exception
Division by zero
Access to an array outside of its bounds
Running out of memory
Running out of disk space
Need for Exception Handling
Dividing the error handling
Unconditional termination & programmer preferred termination
Separating error reporting and error handling
Object destroy problem
#include catch( int a)
int main() { // catch an error
{ cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
71/207
Note that the statement after throw statement in try block is not executed.
Once the exception is thrown the catch block catches the value (here zero) and
handles it.
After that the program continues its normal execution.
Functions Generating Exceptions
C++ allows functions to generate exceptions. These functions cannot be called as an ordinary
function. Enclose the function call with a try catch block.
Syntax:
try
{ function(arg);
}
catch(type arg)
{
------
}
#include void main()
void compute(int a,int b) {
{ int x,y;
int c; if(b==0) coutx>y;
throw b; try
else {
c=a/b; compute(x/y); // fun generating exception
} }
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
72/207
Throwing Mechanisms:
An exception is thrown by using the throw keyword from inside the try block.
A throw expression accepts one parameter, which is passed as an argument to the
exception handler.Eg. throw b;
The throw statement will have the following.
Example:
throw (exception)
throw exception
throw
Catching Mechanisms
If the data type specified by a catch, matches that of the exception, then catch
statement is executed.
When an exception is caught, arg will receive its value
Multiple Catch Statements
A try can have multiplecatches
If there are multiple catches for a try, only one of the matching catch is selected and
that corresponding catch block is executed.
Syntax:
try
{
any statements
if (some condition) throw
value1; else if (some other
condition) throw value2;
else if (some last
condition) throw valueN;
}
catch (type1 name)
72www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
73/207
{
any statements
}
catch (type2 name)
{
any statements
}
catch (typeN name)
{
any statements
}
Example:
#include
void multiple_catch(int value)
{
try
{
if (value==0) //throw an int value
throw 1;
else if (value==1) //throw a char
throw a;
else //throw float
throw 1.1;
}
catch(char c)
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
74/207
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
75/207
void shoex()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
76/207
void main ()
{
try
{
ergen();
throw 10;
}
catch (int)
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
77/207
Example:
#include
void myunexpected ()
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
78/207
Syntax:
bool
uncaught_exceptions.
if
(uncaught_exception(
))
{
//Do not call the function which might throw an exception
}
Otherwise
{
Follow the natural sequence of the destructor Algorithm
}
3.3 STANDARD LIBRARIES:
Streams and Formatted I/O :
A stream is a sequence of bytes (or) conceptually pipe like constructs used for
providing I/O.
Streams provide consistent interface for providing independence from having different
operations for different IO devices.
The source stream that provides data to the program is called the input stream.
The destination stream that receives output from the program is called the output
stream.
C++ STREAM CLASSES:
ios :
It is the base class for istream and ostream.
It is declared as the virtual base class.
It provides the basic support for formatted and unformatted I/O operations.
istream:
Provides facilities for formatted and unformatted input operations.
Functions such as getc(),getline(),read() are declared.
Overloaded extraction operator (>>)
78www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
79/207
ostream:
Provides the facilities for formatted and unformatted output operations.
Putc() and write() functions are declared.
Overloaded insertion operator ( and > operator is overloaded in the istream.
The >variable 1>>.>>variable n ;
The input data are separated by white spaces and should match the type of variable incin. cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
80/207
The difference between getline() and read() is that : getline() terminates when a new
line is entered but read() does not stop when a new line is encountered.
read() stops only when end of file (ctrl + z ) is encountered.
The getline() also stops reading from input if end of file is specified.
FORMATTED I/O OPERATIONS:
1.width() :it specifies the width for display.
it is used in aligning vertical columns.
2.precision() :
it specifies the precision of the floating pointnumber.
default precision is six digits after the decimal
point.
3.fill() :
specifies the character for filling up the unused portion of
field.it is used with width().
4.setf() :
The function specifies format flags that control output display like left (or) right or rightjustification, padding, scientific notation, displaying base number.
5.unsetf():It provides undo operation for the above mentioned operations.
MANIPULATORS:
Manipulators are special functions for formatting.
The choice between manipulators and ios functions to solve formatting problems
sometimes depends on the preference of the user.
Manipulators:
setw()
setprecison()
setfill()
setiosflags()
80www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
81/207
resetiosflags()
Characteristics of manipulators:
Writing our own manipulators is possible.
Manipulators are easy to write and produce more readable codes and make theprogram short.
They need iostream.h and iomanip.h files.
When a manipulator does not take any arguments , it is passed without the ()parenthesis.
Some manipulators are needed in pairs to produce the toggle effect.
They are non-member-functions.
Characteristics of ios functions:
They are single and cannot be combined to have multiple effects.
They need iostream.h file
ios functions are member functions.
The functions do not return the previous status.
3.4 GENERIC PROGRAMMING:
Generic programming means that you are not writing source code that is compiled as-is but that yo
collection of other objects. But there's much more to generic programming. In the context of
C++ .it means to write programs that are evaluated at compile time.
A basic example of generic programming are templates of containers: In a statically
typed language like C++ you would have to declare separate containers that hold integers,
floats, and other types or deal with pointers to void and therefore losing all type information.
Templates which are the C++ way of generic programming leverage this constraint by
letting you define classes where one or more parameters are unspecified at the time you define
the class. When you instance the template later you tell the compiler which type it should use
to create the class out of the template.
Example: templateclass MyContainer
{// Container that deals with an arbitrary type T
81www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
82/207
};
void main()
{
// Make MyContainer take just ints.MyContainer intContainer;
}
3.5 TEMPLATES:
A significant benefit of object oriented programming is reusability of code which
eliminates redundant coding.
An important feature of oops called Templates makes this benefit stronger and
provides the greater flexibility to the languages.
A template allows the construction of family of functions and classes to perform the
same operation on different types.
This provides the generic programming which allows developing the reusable software
component such as classes and function.
There are two types of templates.Function templates
Class templates
Terms which means use the same function or class for different purpose without
changing their basic meaning where the function or class should be defined only once.
Templates are used to achieve reusability which eliminates redundant code.
3.6 CLASS TEMPLATES:
Class templates are used to create generic class witch support different data types.
Syntax:
template
class
{
Member;
Member function;
};
82www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
83/207
Example:
#include
#include
template class complex
{
T real, image;
public:
void getdata()
{
cout>real>>image;
}
void putdata()
{
if(image>0)
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
84/207
3.7 FUNCTION TEMPLATES:
The template declared for function is function template. Function templates are generic
function, which work for any data that is passed to them. The data type is not specified while
declaring the function. It performs appropriate operation depending on the data type we
passed to them.
Syntax:
Template
Return Type Function-name(argument)
{
Function body
}
Example:
Template < class T>
void generic Bubblesort(T Temp GenericArray[]) // template function
1 {
for( int i=0;i
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
85/207
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
86/207
void display(T1 a, T2 b)
{
cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
87/207
3.9 CONTAINERS:
A Container is an object that stores other objects (its elements), and that has methods
for accessing its elements. 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
types of data.
The STL contains three types of containers
Sequence containers
Associative containers
Derived containers
Sequence Containers:
Sequence containers store elements in a linear sequence, like a line. 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.
The following are the types of sequence containers.Vector
List
deque
Element0 Element1 Element2 . Last Element
Associative Containers:
Associative containers are designed to support direct access to elements using keys.
The following are the types of associative containers.
Set
Multiset
Map
Multimap
87www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
88/207
Derived Containers:
The derived containers do not support iterators and therefore we cannot use them for
data manipulation. They support two member functions pop() and push()for implementing
deleting and inserting operations.
The following are the types of associative containers.Stack
Queue
Priority_queue
3.10 ITERATORS:
An iterator is an object that points to an element in a container. We can use iterators
to move through the contents of containers. Iterators are handled just like pointers.
Iterators are classified into five categories depending on the functionality theyimplement:
Input
Output
Forward
Bidirectional
Random Access
Input and output:
Input and Output iterators are the most limited types of iterators: they can perform
sequential single-pass input or output operations.
Forward:
Forward iterators have all the functionality of input iterators and if they are not
constant iterators also the functionality of output iterators, although they are limited to one
direction in which to iterate through a range (forward). All standard containers support at
least forward iterator types.
Bidirectional:
Bidirectional iterators are like forward iterators but can also be iterated through
backwards.
88www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
89/207
Random Access:
Random-access iterators implement all the functionality of bidirectional iterators, and
also have the ability to access ranges non-sequentially: distant elements can be accessed
directly by applying an offset value to an iterator without iterating through all the elements in
between. These iterators have a similar functionality to standard pointers (pointers are
iterators of this category).
3.11 FUNCTION ADAPTORS:
In the context of the C++ programming language, functional refers to a header file
that is part of the C++ Standard Library and provides a number of predefined class templates
for function objects, including arithmetic operations, comparisons, and logical operations.
Instances of these class templates are C++ classes that define a function call operator, and the
instances of these classes can be called as if they were functions. It is possible to perform
very sophisticated operations without actually writing a new function object, simply by
combining predefined function objects and function object adaptors.
Negators:
The negators not1 and not2 are functions which take a unary and a binary predicate,
respectively, and return their complements.template
unary_negate not1(const Predicate& pred)
{
return unary_negate(pred);
}
template
binary_negate not2(const Predicate& pred)
{
return binary_negate(pred);
}
The classes unary_negate and binary_negate only work with function object classes
which have argument types and result type defined. That means, that
Predicate::argument_type and Predicate::result_type for unary function objects and
89www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
90/207
Predicate::first_argument_type, Predicate::second_argument_type and Predicate::result_type
for binary function objects must be accessible to instantiate the negator classes.
vector v;
// fill v with 1 2 3 4
sort (v.begin(), v.end(), not2 (less_equal()) );
Output: 4 3 2 1
Binders:
"The binders bind1st and bind2nd take a function object f of two arguments and a
value x and return a function object of one argument constructed out of f with the first or
second argument correspondingly bound to x.", Imagine that there is a container and you
want to replace all elements less than a certain bound with this bound.
vector v;
// fill v with 4 6 10 3 13 2
int bound = 5;
replace_if (v.begin(), v.end(), bind2nd (less(), bound), bound);
// v: 5 6 10 5 13 5
bind2nd returns a unary function object less that takes only one argument, because the
second argument has previously been bound to the value bound. When the function object is
applied to a dereferenced iterator i, the comparison *i < bound is done by the function-call
operator of less.
Adaptors for pointers to functions:
The STL algorithms and adaptors are designed to take function objects as arguments.
If a usual C++ function shall be used, it has to be wrapped in a function object.
The function ptr_fun takes a unary or a binary function and returns the corresponding
function object. The function-call operator of these function objects simply calls the function
with the arguments provided.
For example, if a vector of character pointers is to be sorted lexicographically with
respect to the character arrays pointed to, the binary C++ function strcmp can be transformedinto a comparison object and can so be used for sorting.
90www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
91/207
vector v;
char* c1 = new char[20]; strcpy (c1, "Tim");
char* c2 = new char[20]; strcpy (c2, "Charles");
char* c3 = new char[20]; strcpy (c3, "Aaron");
v.push_back (c1); v.push_back (c2); v.push_back (c3);
sort (v.begin(), v.end(), ptr_fun (strcmp) );
copy (v.begin(), v.end(), ostream_iterator (cout, " ") );
3.12 ALLOCATORS:
In C++ computer programming, allocators are an important component of the C++
Standard Library. The standard library provides several data structures, such as list and set,
commonly referred to as containers. A common trait among these containers is their ability to
change size during the execution of the program. It encapsulates a memory allocation and
deallocation strategy.
Every standard library component that may need to allocate or release storage, from
std::string, std::vector, and every container except std::array, to std::shared_ptr and
std::function, does so through an Allocator: an object of a class type that satisfies the
following requirements.
Requirements
A, an Allocator type for type T
a, an object of type A
B, the corresponding Allocator type for type U (as obtained by rebinding A)
ptr, a value of type allocator_traits::pointer, obtained by
calling allocator_traits::allocate()
cptr, a value of type allocator_traits::const_pointer, obtained by conversion
from ptr
vptr, a value of type allocator_traits::void_pointer, obtained by conversion from
ptr
cvptr, a value of type allocator_traits::const_void_pointer, obtained by
conversion from cptr or from vptr
91www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
92/207
xptr, a dereferencable pointer to some type X
Some requirements are optional: the template std::allocator_traits supplies the default
implementations for all optional requirements, and all standard library containers and other
allocator-aware classes access the allocator through , not directly.
3.13 PARAMETERIZING THE CLASSES:
A template can be used as a family of classes or functions. It can be considered as a
macro. When an object of a specific type is defined for actual use, the template definition for
that class is substituted with the required data type. Since a template is defined with a
parameter that would be replaced by a specified data type at the time of actual use of the class
or function, the templates are sometimes called parameterized classes or functions.
We can use more than one generic data type in a class template. They are declared
as a comma separated list within the template specification.
Syntax:
template class classname
{
.
..
(Body of the class)
};
3.14 FILE HANDLING CONCEPTS:
OS is the primary interface between the user and the computer. Device driver is a
small program that comes with every device IO operations are performed with the help of
the OS and the device driver. A C++ program does not directly request to the OS. It invokes
a function from a standard library that comes with a C++ compiler, when it is installed.
Text and Binary Files:
Text stream:
deals with information which is in ASCII form.
if key is pressed, Carriage return and Line Feed characters are inserted. This
92www.cseitquestions.in
st ::a ocator_traits
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
93/207
is known as conversion. The text stream files can be opened by any editor. Text files
are more general.
Binary streams:
binary values are inserted
no conversion takes place.
The binary stream files are restricted to the application that creates the file. Binary files are
not flexible.
Dealing With Text Files:
ifstream < filename> - read only file
ofstream - output /write only file
fstream - both input/read and output /write file.
Manipulating Files Opening Files:
Files can be opened using two methods
(i) using constructors (ii)
using open functions
File Modes:
When a file is opened, it must be specified how it is to be opened. This means
whether to create it from new or overwrite it and whether it's text or binary, read or write and
if the content is to be appended to it.
In order to open a file with a stream object open() member function is used.
open (filename, mode);
ios::ate
Write all output to the end of file (even if file position pointer is moved with seekp)
ios::app
Open a file for output and move to the end of the existing data (normally used to
append data to a file, but data can be written anywhere in the file
ios::in
The original file (if it exists) will not be truncated
ios::outOpen a file for output (default for ofstream objects)
93www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
94/207
ios::trunc
Discard the file's contents if it exists (this is also the default action for ios::out, if
ios::ate, ios::app, or ios::in are not specified)
ios::binary
Opens the file in binary mode (the default is text mode)
ios::nocreate
Open fails if the file does not exist
ios::noreplace
Open files if the file already exists.
Inserting data somewhere in a sequential file would require that the entire file be
rewritten. It is possible, however, to add data to the end of a file without rewriting the file.
Adding data to the end of an existing file is called appending.
fout.open("filename.dat", ios::app) //open file for appending
Program to append to the contents of a file
#include
#include
int main(void)
{
string name, dummy;
int number, i, age;
ofstream fout;
cout>number;
getline (cin,dummy);
fout.open ("name_age.dat",ios::app); // open file for appending
assert (!fout.fail( ));
for(i=1, i
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
95/207
getline(cin,age);
fout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
96/207
char code[6];
char name[20];
int i;
}r;
int main()
{
std::fstream file("Temp.dat",std::ios::trunc|std::ios::in|std::ios::out|std::ios::binary);
if(!file)
{
std::cout>r.i;
file.write((char *)&r,sizeof(r));
std::cout
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
97/207
UNIT IV
ADVANCED NON-LINEAR DATA STRUCTURES
AVL trees B-Trees Red-Black trees Splay trees - Binomial Heaps Fibonacci
HeapsDisjoint Sets Amortized Analysis accounting methodpotential method
aggregate analysis.
TREE INTRODUCTION
Tree
A tree is a collection of nodes. The collection can be empty; otherwise a tree consists
of a specially designed node called root, and one or more non empty sub trees T1, T2, ,Tk, each of whose roots are connected by a directed edge from root.
Fig: Generic tree
Fig: A tree
Root
The root is the first and top most nodes in the hierarchical arrangement of data items.
A node which does not have a parent node is called root node. In the above tree, the root is
A.
Node
Each data item present in the tree is called a node.It is the basic data structures that
specifies the data information and have links to other data items. Example node A, B, ..,,
Q.
Leaf
A node which doesnt have children is called leaf or Terminal node. In the abovetree B, C, H, I, K, L, M, N, P, Q are leaf node.
97www.cseitquestions.in
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
98/207
Siblings
Children of the same parents are said to be siblings.In the above tree B, C, D, E, F ,G
are siblings, I,J are siblings, K, L, M are siblings, P, Q are siblings.
Path
A pathfrom node n1to nkis defined as a sequence of nodes n1, n2, . . . , nksuch that
niis the parent of ni+1for 1
7/25/2019 THIRD SEMESTER PROGRAMMING AND DATA STRUCTURES-2 NOTES FOR 5 UNITS REGULATION 2013Cs6301 Notes
99/207
Terminal node