OOPS_[Detailed & Advanced]
OOPS_[Detailed & Advanced]
Operator Overloading
Dr. Prikshat Kumar Angra, Lovely Professional University
Type Conversion
Dr. Prikshat Kumar Angra, Lovely Professional University
Run - time Polymorphism
Dr. Prikshat Kumar Angra, Lovely Professional University
Virtual Functions
Dr. Prikshat Kumar Angra, Lovely Professional University
Working with Streams and Files
Dr. Prikshat Kumar Angra, Lovely Professional University
More on Files
Dr. Prikshat Kumar Angra, Lovely Professional University
Objectives
After studying this unit, you will be able to:
Recognize the basic concept of object-oriented programming
Describe the OOP languages
Understand Basics of C++
Compare the procedural Oriented and object-oriented programming
Introduction
Over the last few decades, programming practices have changed dramatically. As more
programmers gained competence, previously undiscovered difficulties began to emerge. The
programming community became increasingly worried about the programming philosophy they
use and the methodologies they use in software development.
Productivity, reliability, cost effectiveness, reusability, and other factors began to become key
concerns. Many conscious attempts were made to comprehend these issues and find potential
answers. This is precisely why a growing number of programming languages have been developed
and are still being developed. Furthermore, techniques to programme creation have been the
subject of extensive research, resulting in the development of several frameworks. The object-
oriented programming method, or simply OOP, is one such approach, and it is perhaps the most
common.
C++ programming's main goal is to introduce the concept of object orientation to the C
programming language.
Inheritance, data binding, polymorphism, and other notions are all part of the Object Oriented
Programming paradigm.
They occupy space in memory that keeps its state and is operated on by the defined operations on
the object. Each object contains data and code to manipulate the data.
Notes: -Objects can interact without having to know details of each other data or code.
2. Classes: A class represents a set of related objects. The object has some attributes, whose
value consist much of the state of an object. The class of an object defines what attributes an object
has. The entire set of data and code of an object can be made a user-defined data type with the help
of a class.
Classes are user defined data types that behave like the built-in types of a programming language.
Classes have an interface that defines which part of an object of a class can be accessed from outside
and how. A class body that implements the operations in the interface, and the instance variables
that contain the state of an object of that class.
Notes:- A class is a data-type that has its own members i.e. data members and member
functions. It is the blueprint for an object in objects oriented programming language. It is the basic
building block of object oriented programming in c++.
The data and the operation of a class can be declared as one of the three types:
(a) Public: These are declarations that are accessible from outside the class to anyone who can
access an object of this class.
(b) Protected: These are declarations that are accessible from outside the class to anyone who
can access an object of this class.
(c) Private: These are declarations that are accessible only from within the class itself.
Syntax of class
class class_name {
data_type data_name;
return_type method_name(parameters);
}
3. Data abstraction: - Data abstraction or Data Hiding is the concept of hiding data and
showing only relevant data to the final user. It is also an important part object oriented
programing.
better, when we ride a bike we only
know that pressing the brake will stop the bike and rotating the throttle will accelerate but
you don't know how it works and it is also not think we should know that's why this is
done from the same as a concept data abstraction.
In C plus plus programming language write two ways using which we can accomplish data
1. using class
2. using header file
Example: - We can represents essential features without including background details and
explanations.
index of text book.
class School
{
void sixthc lass();
void seventhclass();
void tenthclass();
}
Notes: - Inheritance allows us to create a new class (derived class) from an existing class (base
class).
single inheritance
multiple inheritance
multi level inheritance
Hierarchical inheritance
hybrid inheritance
Caution: - Keep in mind that each subclass defines only those features that are unique to it.
6. Polymorphism:-
Polymorphism means the ability to take more than one form. An operation may exhibit different
behavior in different instances. The behavior depends upon the types of the data used in the
operation. For example considering the operator plus (+).
16 + 4 = 20
Example: - A person can have more than one behavior depending upon the situation. like a
woman a mother, manager and a daughter And this define her behavior. This is from where the
concept of polymorphism came from.
In c++ programming language, polymorphism is achieved using two ways. They are operator
overloading and function overloading.
7. Dynamic Binding:-
Binding refers to the process of converting identifiers (such as variable and performance names)
into addresses. Binding is done for each variable and functions. For functions, it means that
matching the call with the right function definition by the compiler. It takes place either at compile
time or at runtime.
This is associated with polymorphism and inheritance. A function call associated with a
polymorphic reference depends on the dynamic type of that reference. For example in the above
figure, by inheritance, every object will have this procedure. Its algorithm is, however, unique to
each object so the procedure will be redefined in each class that defines the objects. At run-time, the
code matching the object under reference will be called.
8. Message Passing
Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a function
in the receiving object that generates the desired results. Message passing involves specifying the
name of the object, the name of the function and the information to be sent.
Example
#include<iostream>
using namespace std;
class demo{
public:
int f_num,s_num;
sum(int a,int b){
cout<<a+b;
}
};
main(){
demo d1;
d1.sum(d1.f_num=10,d1.s_num=39);
return 0;
}
program grow in size. A language that is specially designed to support the OOP concepts makes it
easier to implement them.
To claim that they are object-oriented they should support several concepts of OOP.
Depending upon the features they support, they are classified into the following categories:
1. Object-based programming languages.
2. Object-oriented programming languages.
Languages that support programming with objects are said to be object-based programming
languages. These do not support inheritance and dynamic binding ADA is a typical example Object
oriented programming incorporates all of objects-based programming features along with two
additional feature, namely, inheritance and dynamic binding.
Languages that support these features:-
C++
.NET
Java
PHP
C#
Python
Ruby
In the modern programming parlance, at least in most of the commercial and business applications
areas, programming has been made independent of the target machine. This machine independent
characteristic of programming has given rise to a number of different methodologies in which
programs can now be developed. We will particularly concern ourselves with two broad
programming approaches or paradigm as they are called in the present context.
1. Procedure-oriented paradigm
2. Object-oriented paradigm
You organize the related data items into C structures and write the necessary functions
(procedures) to manipulate the data and, in the process, complete the sequence of tasks that solve
your problem. Structure of procedure oriented paradigm is shown in following figure.
Many key data items are put as global in a multi-function software so that they can be accessible by
all functions. It's possible that each function has its own set of local data. Global data are more
vulnerable to a function's unintended alteration. It's difficult to figure out which data is used by
which function in a huge software. If we need to make changes to an external data structure, we
must likewise make changes to any functions that access the data. Bugs will be able to get in
through this opening.
Another serious drawback with the procedural approach is that we do not model real world
problems very well. This is because functions are action-oriented and do not really corresponding
to the element of the problem.
relatively independent units that are easier to maintain and extend. You can also share code among
objects through inheritance.
Secondly, OOP has nothing to do with any programming language, although a programming
language that supports OOP makes it easier to implement the object-oriented techniques. As
you will see shortly, with some discipline, you can use objects even in C programs.
Object-Oriented Databases: They are also called Object Database Management Systems
(ODBMS). These databases store objects instead of data, such as real numbers and
integers. Objects consist of the following:
o Attributes: Attributes are data that define the traits of an object. This data can be
as simple as integers and real numbers. It can also be a reference to a complex
object.
o Methods: They define the behavior and are also called functions or procedures.
Simulation and modelling: Another area where OOP approach criteria might be counted
is system modelling. Because OOP programmers are easier to grasp, it is preferable to
represent a system in a simpler form when using the OOP approach.
AI and expert systems: These are computer applications that are developed to solve
complex problems pertaining to a specific domain, which is at a level far beyond the reach
of a human brain.
It has the following characteristics:
o Reliable
o Highly responsive
o Understandable
o High-performance
Neural networks and parallel programming: It address the problem of prediction and
approximation of complex time-varying systems. Firstly, the entire time-varying process is
split into several time intervals or slots. Then, neural networks are developed in a
particular time interval to disperse the load of various networks. OOP simplifies the entire
process by simplifying the approximation and prediction ability of networks.
Example
#include<iostream>
using namespace std;
class find_sum{
public:
int x,y;
int sum();
};
int find_sum ::sum(){
return x+y;
}
Example
#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
double Box::getWidth(void) {
return width ;
}
Summary
Programming practices have evolved considerably over the past few decades.
By the end of last decade, millions and millions of lines of codes have been designed and
implemented all over the word.
The main objective is to reuse these lines of codes. More and more software development
projects were software crisis.
It is this immediate crisis that necessitated the development of object-oriented approach
which supports reusability of the existing code.
Software is not manufactured. It is evolved or developed after passing through various
developmental phases including study, analysis, design, implementation, and
maintenance.
Conventional programming using high level languages such as COBOL, FORTRAN and C
is commonly known as procedures-oriented programming.
In order to solve a problem, a hierarchical decomposition has been used to specify the
tasks to be completed.
OOP is a method of designing and implementing software.
Since OOP enables you to remain close to the conceptual, higher-level model of the real
world problem, you can manage the complexity better than with approaches that force
you to map the problem to fit the features of the language.
Some essential concepts that make a programming approach object-oriented are objects,
classes, Data abstraction, Data encapsulation, Inheritance, Polymorphism, dynamic
binding and message passing.
The data and the operation of a class can be disclosed public, protected or private. OOP
provides greater programmer productivity, better quality of software and lesser
maintenance cost.
Keywords
Classes: A class represents a set of related objects.
Data Abstraction: Abstraction refers to the act of representing essential-features without
including the background details or explanations.
Data Encapsulation: The wrapping up to data and functions into a single unit (class) is known as
encapsulation.
Design: The term design describes both a final software system and a process by which it is
developed.
Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
Message Passing: Message passing is another feature of object-oriented programming.
Object-oriented Programming Paradigm: The term object-oriented programming (OOP) is
widely used, but experts do not seem to agree on its exact definition.
Objects: Objects are the basic run-time entities in an object-oriented system.
Polymorphism: Polymorphism means the ability to take more than one form.
Self Assessment
B. Data hiding
C. Encapsulation
D. Polymorphism
5. Which of the following is correct about class?
A. class can have member functions while structure cannot.
B. class data members are public by default while that of structure are private.
C. Pointer to structure or classes cannot be declared.
D. class data members are private by default while that of structure are public by default.
7. Which of the following OOP concept is not true for the C++ programming language?
A. A class must have member functions
B. C++ Program can be easily written without the use of classes
C. At least one instance should be declared within the C++ program
D. C++ Program must contain at least one class
8. What is the extra feature in classes which was not in the structures?
A. Member functions
B. Data members
C. Public access specifier
D. Static Data allowed
12. Which among the following feature does not come under the concept of OOPS?
A. Platform independent
B. Data binding
C. Data hiding
D. Message passing
13. The combination of abstraction of the data and code is viewed in________.
A. Inheritance
B. Class
C. Object
D. Interfaces
15. Which syntax among the following shows that a member is private in a class?
A. private::Name(parameters)
B. private: function Name(parameters)
C. private(function Name(parameters))
D. private function Name(parameters)
6. B 7. D 8. A 9. D 10. B
Review Questions
1. Discuss basic concepts of C++ in detail.
2. Inheritance is the process by which objects of one class acquire the properties of
objects of another class. Analyze.
3. Examine what are the benefits of OOP?
4. Compare what you look for in the problem description when applying object-oriented
approach in contrast to the procedural approach. Illustrate with some practical
examples.
5. What is OOP? Explain the applications of object oriented programming in detail.
6. Differentiate procedural programming and object oriented programming.
7. Write programs that demonstrate working of classes and objects.
Further Readings
E. Balagurusamy, Object-oriented Programming through C++, Tata McGraw Hill.
Herbert Schildt, The Complete Reference C++, Tata Mc Graw Hill.
Robert Lafore, Object-oriented Programming in Turbo C++, Galgotia Publications
Web Links
https://en.wikipedia.org/wiki/Object-oriented_programming
www.web-source.net
www.webopedia.com
Objectives
Introduction
When an object is created all the members of the object are allocated memory spaces. Each object
has its individual copy of member variables. However, the data members are not initialized
automatically. If left uninitialized these members contain garbage values. Therefore, it is important
that the data members are initialized to meaningful values at the time of object creation.
Conventional methods of initializing data members have lot of limitations. In this unit you will
learn alternative and more elegant ways initializing data members to initial values.
When a C++ program runs it invariably creates certain objects in the memory and when the
program exits the objects must be destroyed so that the memory could be reclaimed for further use.
C++ provides mechanisms to cater to the above two necessary activities through constructors and
destructors methods.
17
Notes
Notes: Constructor has the same name as the class. Constructor is public in the class.
Constructor does not have any return type.
While writing a constructor function the following points must be kept in mind:
1. The name of constructor method must be the same as the class name in which it is defined.
2. A constructor method must be a public method.
3. Constructor method does not return any value.
4. A constructor method may or may not have parameters.
Let us examine a few classes for illustration purpose. The class abc as defined below does not have
user defined constructor method.
classabc
{
}
main()
{
}
intx,y;
abcmyabc;
The main function above an object named myabc has been created which belongs to abc class
defined above. Since class abc does not have any constructor method, the default constructor
method of C++ will be called which will initialize the member variables as:
myabc.x=0 and myabc.y=0.
Let us now redefine myabc class and incorporate an explicit constructor method as shown
below:
classabc
Observed that myabc class has now a constructor defined to except two parameters of integer type.
We can now create an object of myabc class passing two integer values for its construction, as listed
below:
main()
{
18
Notes
Unit 02: Constructors and Destructors
abcmyabc(100,200);
;
}
In the main function myabc object is created value 100 is stored in data variable x and 200 is stored
in data variable y. There is another way of creating an object as shown below.
main()
{
myabc=abc(100,200);
;
}
Both the syntaxes for creating the class are identical in effect. The choice is left to the programmer.
There are other possibilities as well. Consider the following class differentials:
classabc
{
intx,y; public:
abc();
}
abc::abc()
{
x=100; y=200;
}
In this class constructor has been defined to have no parameter. When an object of this class is
created the programmer does not have to pass any parameter and yet the data variables x,y are
initialized to 100 and 200 respectively.
Finally, look at the class differentials as given below:
classabc
intx,y; public:
abc();
abc(int);
abc(int, int);
abc::abc()
{
LOVELY PROFESSIONAL UNIVERSITY
19
Notes
x=100; y=200;
}
abc::abc(int a)
x=a; y=200;
}
abc::abc(int a)
x=100;
y=a;
}
Class myabc has three constructors having no parameter, one parameter and two parameters
respectively. When an object to this class is created depending on number of parameters one of
these constructors is selected and is automatically executed.
Types of constructor
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
20
Notes
Unit 02: Constructors and Destructors
Destructor
Destructors are typically used to de-allocate memory. Also, they are used to clean up for objects
and class members when the object gets terminated.
When should you define your own destructor function? In many cases you do not need a
destructor function. However, if your class created dynamic objects, then you need to define your
own destructor in which you will delete the dynamic objects. This is because dynamic objects
cannot be deleted on their own. So, when the object is destroyed, the dynamic objects are deleted by
the destructor function you define.
A destructor function has the same name as the class, and does not have a returned value. However
you must precede the destructor with the tilde sign, which is ~ .
The following code illustrates the use of a destructor against dynamic objects:
#include <iostream> using namespace std;
class Calculator
{
public:
int *num1;
int *num2;
*num2 =ident2;
~Calculator()
{
delete num1;
delete num2;
}
int add(){
int sum=*num1+*num2;
return sum;
}
};
int main()
{
Calculator myObject(20,20);
int result = myObject.add();
cout<< result;
21
Notes
Lab Exercise: Program to see how Constructor and Destructor are called.
class A
{
// constructor
A()
{
cout<< "Constructor called";
}
// destructor
~A()
{
cout<< "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Output:-
Constructor called
Constructor called
Destructor called
Destructor called
22
Notes
Unit 02: Constructors and Destructors
2.2 Difference between Constructor and Destructor in C++
Constructors Destructors
The constructor initializes the class and allots If the object is no longer required, then
the memory to an object. destructors demolish the objects.
A constructor allows an object to initialize some A destructor allows an object to execute some
of its value before it is used. code at the time of its destruction.
When it comes to constructors, there can be When it comes to destructors, there is constantly
various constructors in a class. a single destructor in the class.
They are often called in successive order. They are often called in reverse order of
constructor.
{
x=a.x;
y=a.y;
}
Suppose we create an object myabc1 with two integer parameters as shown below:
abc myabc1(1,2);
Having created myabc1, we can create another object of abc type, say myabc2 from myabc1, as
shown below:
myabc2=abc(& myabc1);
The data values of myabc1 will be copied into the corresponding data variables of object myabc2.
Another way of activating copy constructor is through assignment operator. Copy constructors
come into play when an object is assigned another object of the same type, as shown below:
abc myabc1(1,2);
abc myabc2;
myabc2=myabc1;
Actually assignment operator(=) has been overloaded in C++ so that copy constructor is invoked
whenever an object is assigned another object of the same type.
23
Notes
(a) If a new object has to be created before the copying can occur, the copy constructor
isused.
(b) Ifanewobjectdoesnothavetobecreatedbeforethecopyingcanoccur,theassignment
operator isused.
Example:-
#include <iostream.h>
#include <conio.h>
classdyncons
{
int * p;
public:
dyncons()
{
p=new int;
*p=100;
}
dyncons(int v)
{
p=new int;
*p=v;
}
int dis()
{
return(*p);
}
};
int main()
{
clrscr();
dyncons o, o1(90);
24
Notes
Unit 02: Constructors and Destructors
cout<<"The value of object o's p is:";
cout<<o.dis();
cout<<"\nThe value of object 01's p is:"<<o1.dis();
return 0;
}
Output:
The value of object o's p is:100
The value of object 01's p is:90
classdist
{
int m, cm; public:
dist(int x, int y);
};
dist::dist(int x, int y)
{
m = x; n=y;
}
main()
{
dist d(4,2);
d. show ();
}
#include <iostream.h>
class interest
{
int principal, rate, year;
float amount;
25
Notes
\
\
\
};
main ( )
{
interest i1(1000,2);
interest i2(1000, 2,15);
il.cal();
i2.cal();
}
26
Notes
Unit 02: Constructors and Destructors
Lab Exercise
//# Program Default constructor
#include<iostream>
using namespace std;
class constructor{
private:
intx,y;
public:
constructor(){
x=10;
y=90;
cout<<"Sum of x and y is :"<<x+y;
}
};
int main(){
constructor c;
return 0;
}
Output
Lab Exercise
// Program Parameterizedconstructor
#include<iostream>
using namespace std;
class constructor{
private:
intx,y;
public:
constructor(inta,int b){
x=a;
y=b;
cout<<"Sum of x and y is :"<<x+y;
}
};
int main(){
LOVELY PROFESSIONAL UNIVERSITY
27
Notes
Lab Exercise
// Program Copy Constructor
#include<iostream>
using namespace std;
classcopyconstructor
{
private:
int x, y;
public:
copyconstructor(int x1, int y1)
{
x = x1;
y = y1;
}
copyconstructor (constcopyconstructor&sam)
{
x = sam.x;
y = sam.y;
}
void display()
{
cout<<x<<" "<<y<<endl;
}
};
int main()
{
copyconstructor obj1(10, 15);
copyconstructor obj2 = obj1;
cout<<"Constructor : ";
28
Notes
Unit 02: Constructors and Destructors
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Output
Lab Exercise
// Program Dynamic Constructor
#include <iostream>
using namespace std;
class demo {
int* p;
public:
demo()
{
p = new int;
*p = 500;
}
void display()
{
cout<<"Dynamic constructor"<<endl;
cout<< *p <<endl;
}
};
int main()
{ demoobj = demo();
obj.display();
return 0;
}
demo()
{
p = new int;
*p = 500;
LOVELY PROFESSIONAL UNIVERSITY
29
Notes
demo(int a)
{
p = new int;
*p = a;
}
Output
}
demo(inta,int b){
x=a;
y=b;
cout<<"Sum of x and y is"<<x+y;
}
};
30
Notes
Unit 02: Constructors and Destructors
main(){
demo d1,d2(90,59);
}
Output
2.8 Destructors
Constructors create an object, allocate memory space to the data members and initialize the data
members to appropriate values; at the time of object creation. Another member method called
destructor does just the opposite when the program creating an object exits, thereby freeing the
memory.
A destructive method has the following characteristics:
1. Name of the destructor method is the same as the name of the class preceded by a tilde (~).
2. The destructor method does not take any argument.
3. It does not return any value.
The following codes snippet shows the class student with the destructor method;
Example
#include <iostream>
using namespace std;
class student
{
public:
student()
{
cout<<"Constructor Invoked"<<endl;
}
~student()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main()
{
31
Notes
Summary
A constructor is a member function of a class, having the same name as its class and which
is called automatically each time an object of that class it created.
It is used for initializing the member variables with desired initial values. A variable
(including structure and array type) in C++ may be initialized with a value at the time of
its declaration.
The responsibility of initialization may be shifted, however, to the compiler by including a
member function called constructor.
A class constructor, if defined, is called whenever a program created an object of that class.
Constructors are public member unless otherwise there is a good reason against.
A constructor may take argument (s). A constructor may take no argument(s) is known as
default constructor.
A constructor may also have parameter (s) or argument (s), which can be provided at the
time of creating an object of that class.
C++ classes are derived data types and so they have constructor (s). Copy constructor is
called whenever an instance of same type is assigned to another instance of the same class.
If a constructor is called with a smaller number of arguments than required an error
occurs. Every time an object is created its constructor is invoked.
The functions that is automatically called when an object is no more required is known as
destructor. It is also a member function very much like constructors but with an opposite
intent.
Keywords
Constructor: A member function having the same name as its class and that initializes class objects
with legal initial values.
Copy Constructor: A constructor that initializes an object with the data values of another object.
Default Constructor: A constructor that takes no arguments.
Destructor: A member function having the same name as its class but preceded by ~ sign and that
de initializes an object before it goes out of scope.
Self-Assessment
1. Which of the followings is/are automatically added to every class, if we do not write our
own?
A. Copy Constructor
B. Assignment Operator
C. A constructor without any parameter
D. All of the above
32
Notes
Unit 02: Constructors and Destructors
class Point {
};
int main()
Point t1;
return 0;
A. Compiler Error
B. Runtime Error
C. Constructor called
D. None of Above
class demo{
public:
intf_num,s_num;
sum(inta,int b){
cout<<a+b;
};
main(){
demo d1;
d1.sum(d1.f_num=10,d1.s_num=20);
33
Notes
A. 49
B. 50
C. 30
D. 10
7.
objects.
A. Run time construction
B. Dynamic construction
C. Initial construction
D. Memory allocator
10. Does constructor overloading include different return types for constructors to be
overloaded?
a. Yes, if return types are different, signature becomes different
b. Yes, because return types can differentiate two functions
c.
d. turn type
34
Notes
Unit 02: Constructors and Destructors
12. Which is executed automatically when the control reaches the end of the class scope?
a. Constructor
b. Destructor
c. Overloading
d. Copy constructor
14.
a. Class
b. Object
c. Constructor
d. Destructor
15. runtime
depending upon the situation.
a. Dynamic initialization
b. Run time initialization
c. Static initialization
d. Variable initialization
6. A 7. B 8. C 9. C 10. D
Review Questions
1. Write a program to calculate prime number using constructor.
2. Is there any difference between obj x; and objx();? Explain.
3. Can one constructor of a class call another constructor of the same class to initialize the this
object? Justify your answers with an example.
4.
5. Explain constructor and different types of constructor with suitable example.
6. Write a program that demonstrate working of copy constructor.
7. What about returning a local variable by value? Does the local exist as a separate object, or
does it get optimized away?
35
Notes
Further Readings
E Balagurusamy; Object Oriented Programming with C++; Tata McGraw-Hill.
Herbert Schildt; The Complete Reference C++; Tata McGraw Hill. Robert Lafore;
Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://en.wikipedia.org/wiki/Object-oriented_programming
www.web-source.net
www.webopedia.com
36
Notes
Objectives
After studying this unit, you will be able to:
Understand the functions
Describe the function overloading
Explain the inline functions
Understand friend function
Analyze C++ Static Data Members & Functions
Define polymorphism in C++
Introduction
A function is a code module that only does one thing. Sorting, searching for a specific item, and
inverting a square matrix are some instances. After a function is built, it is thoroughly tested.
Following that, it is added to the library of functions. A user can use a library function as often as
they like. This concept enhances software robustness while simultaneously shortening the time it
takes to develop code. System-defined and user-defined functions are the two types of functions.
A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
Caution: In case you design your main method in such a way that it must return a value to
the caller, then it must return an integer type value and therefore you must specify return type to be
int.
Library Functions
It is already present inside the header file which we always include at the beginning of a
program.
You just have to type the name of a function and use it along with the proper syntax.
User-defined Function
User-defined function is a type of function in which we have to write a body of a function and call
Syntax:-
return_data_type function_name (data_type arguments);
2. Function Definition: Function definition function definition means just writing the body
of a function means we are just going to write the body of the function what kind of work
we can do with the function we are just write the logic they are a body of the function
consists of the statements, which are going to be perform a specific task like a sub routine or
a sub program, it is also known as the procedure we are writing the some of the lines there
we are writing some of the code there that is used to perform some of this specific task.
Function definition means just writing the body of a function. A body of a function consists of
definition of function is how
implemented using code.
Syntax:-
int sum(int a,int b)
{
int c;
c=a+b;
return c;
}
3. Function Call: While creating a C++ function, you give a definition of what the function
has to do. To use a function, you will have to call or invoke that function.
Function call has two methods.
1. Call by value
2. Call by reference
1. Call by value: This method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. By default, C++ uses call by value to
pass arguments.
2. Call by reference: This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual argument used in
the call. This means that changes made to the parameter affect the argument.
Example
#include<iostream>
using namespace std;
int sum(int x,int y)
{
return x+y;
}
int main(){
int a,b;
cout<<"Enter two numbers";
cin>>a>>b;
cout<<"Sum of entered number using call by value is = "<<sum(a,b);
return 0;
}
Output
2. Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
Example
#include <iostream>
using namespace std;
inline int display_number(int n){
cout<<"Number is "<< n<<endl;
}
int main() {
display_number(50);
display_number(150);
display_number(200);
return 0;
}
Output
Example
#include <iostream>
using namespace std;
class demo {
public:
int n=100;
char ch='A';
void disp(demo d){
cout<<d.n<<endl;
cout<<d.ch<<endl;
}
};
int main() {
cout<<"Passing object to function"<<endl;
demo obj;
obj.disp(obj);
return 0;
}
Output
Syntax
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Example
#include <iostream>
using namespace std;
class rectangle{
int a;
public:
friend void disp(rectangle r);
void get_length(int l);
};
void rectangle::get_length(int l){
a=l;
}
void disp( rectangle r){
cout<<"Entered length of rectangle is"<<r.a;
}
main(){
rectangle r;
r.get_length(10);
disp(r);
}
Output
Class class_name{
private:
static data_member;
public:
static return_type function_name()
{
//body
}
};
Example
#include <iostream>
using namespace std;
class Demo
{
private:
static int a;
public:
static void fun()
{
cout <<"Value of a: " << a << endl;
}
};
int Demo :: a =500;
int main()
{
Demo obj;
obj.fun();
return 0;
}
Output
arguments. This is something similar to a particular word having several different meanings
depending on the context.
Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface. This means that a general class of operations may be accessed in
the same manner even though specific actions associated with each operation may differ.
Polymorphism is extensively used in implementing inheritance as shown below.
Polymorphism can be implemented using operator and function overloading, where the same
operator and function works differently on different arguments producing different results. These
polymorphisms are brought into effect at compile time itself, hence is known as early binding, static
binding, static linking or compile time polymorphism.
return (a + b);
}
short sum(short a, short b)
{
return (a + b);
}
long sum(long a, long b)
{
return (a + b);
}
float sum(double a, double b)
{
return (a + b);
}
Overloaded functions have the same name but different number and type of arguments. They can
differ either by number of arguments or type of arguments or both. However, two overloaded
function cannot differ only by the return type.
Example
#include<iostream>
using namespace std;
class sample{
public:
int chk_num(){
int a=10;
cout<<"Value of a is "<< a<<endl;
}
int chk_num(int a){
if(a%2==0)
cout<<"Number is even" << a <<endl;
else
cout<<"Number is odd" << a <<endl;
}
float chk_num(float x, float y)
{
cout<<"Sum of floating point number is "<< x+y<<endl;
}
};
main(){
sample obj;
obj.chk_num();
obj.chk_num(15);
obj.chk_num(15.12,25);
Output
Summary
An application written in C++ may have a number of classes. One of these classes must contain one
(and only one) method called main method. Although a private main method is permissible in C++
it is seldom used. For all practical purposes the main method should be declared as public method.
A function may take zero or more arguments when called. The number and type of arguments that
a function may take is defined in the function itself. If a function call fails to comply by the number
and type of argument(s), the compiler reports the same as error. When any program is compiled the
output of compilation is a set of machine language instructions, which is in executable program.
When a program is run, this complied copy of program is put into memory. C++ functions can
have arguments having default values. The default values are given in the function prototype
declaration. Prototype of a function is the function without its body. The C++ compiler needs to
about a function before you call it, and you can let the compiler know about a function is two ways
by defining it before you call it or by specifying the function prototypes before you call it.
Keywords
Function: The best way to develop and maintain a large program is to divide it into several smaller
program modules of which are more manageable than the original program. Modules are written in
C++ as classes and functions. A function is invoked by a function call. The function call mentions
the function by name and provides information that the called function needs to perform its task.
Function Declaration
its arguments.
Function Overloading: In C++, it is possible to define several function with the same name,
performing different actions. The functions must only differ in their argument lists. Otherwise,
function overloading is the process of using the same name for two or more functions.
Function Prototype: A function prototype declares the return-type of the function that declares the
number, the types and order of the parameters, the function expects to receive. The function
prototype enables the compiler to verify that functions are called correctly.
Inline Function: A function definition such that each call to the function is, in effect, replaced by
the statements that define the function.
Self Assessment
1. Which of the following function / types of function cannot have default parameters?
A. Member function of class
B. Main()
C. Member function of structure
D. None of above
7. What are the two advantage of function objects than the function call?
A. It contains a state
B. It is a type
C. It contains a state & It is a type
D. It contains a prototype
9.
A. function declaration
B. function definition
C. main function
D. block function
C. common
D. const
12. Which is the correct syntax for declaring static data member?
A. static mamberName dataType;
B. dataType static memberName;
C. memberName static dataType;
D. static dataType memberName;
return X + Y;
return X + Y;
int main()
return 0;
A. 11 12.1
B. 12.1 11
C. 11 12
D. Compile time error
6. A 7. C 8. C 9. A 10. B
Review Questions
1. What is function prototyping? Why is it necessary? When is it not necessary?
2. What is purpose of inline function?
3. Differentiate between the following:
(a) void main()
(b) int main()
(c) int main(int argn, char argv[])
4. In which cases will declare a member function to be friend?
5. Write a program that uses overloaded member functions for converting temperature from
Celsius to Kelvin scale.
6. To calculate the area of circle, rectangle and triangle using function overloading.
7. Do inline functions improve performance?
8. How can inline functions help with the tradeoff of safety vs. speed?
9. Write a program that demonstrate working of function overloading.
10. Write a program that demonstrates working of inline functions.
Further Readings
E Balagurusamy; Object Oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill. Robert Lafore;
Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://en.wikipedia.org/wiki/Object-oriented_programming
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
The ability to reuse code is a key element of OOP. The concept of reusability is highly supported in
C++. The C++ classes can be reused in a variety of ways. Other programmers can use a class once it
has been written and tested. The properties Notes of existing classes can be reused to create new
classes.
INHERITANCE is the process of creating a new class from an existing one. Because every object of
the defined class "is" also an object of the inherited class type, this is sometimes referred to as a "IS-
A" relationship. The previous class is known as the 'BASE' class, whereas the new class is known as
the 'DERIVED' class or sub-class.
Notes:
The capability of a class to derive properties and characteristics from another class is called
Inheritance.
Inheritance is a process in which one object acquires all the properties and behaviours of
its parent object automatically
}
The colon (:) indicates that the derivedclassname class is derived from the baseclassname class. The
access_specifier or the visibility mode is optional and, if present, may be public, private or
protected. By default it is private. Visibility mode describes the accessibility status of derived
features. For example,
class xyz //base class
{
//members of xyz
};
class ABC: public xyz //public derivation
{
//members of ABC
};
class ABC : XYZ //private derivation (by default)
{
//members of ABC
};
In inheritance, some of the base class data elements and member functions are inherited into the
derived class and some are not. We can add our own data and member functions and thus extend
the functionality of the base class.
1. Public Mode
2. Private Mode
3. Protected Mode
1. Public Mode: If we derive a sub class from a public base class. Then the public member
of the base class will become public in the derived class and protected members of the
base class will become protected in derived class.
2. Private Mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived class.
3. Protected Mode: If we derive a sub class from a protected base class. Then both public
member and protected members of the base class will become protected in derived class.
1. Single Inheritance
When a class inherits from a single base class, it is referred to as single inheritance.
Example
#include <iostream>
using namespace std;
class base
{
public:
int x;
voidgetdata()
{
cout<< "Enter the value of x = "; cin>> x;
}
};
class derive : public base
{
private:
int y;
public:
voidreaddata()
{
cout<< "Enter the value of y = "; cin>> y;
}
void product()
{
cout<< "Product = " << x * y;
}
};
int main()
{
derive a;
a.getdata();
a.readdata();
a.product();
return 0;
}
Output
2. Multiple Inheritance
When a class inherits from a two base classes, it is referred to as multiple inheritance.
Example
#include<iostream>
using namespace std;
class A
{
public:
int x;
voidget_data()
{
cout<< "enter value of x: ";
cin>> x;
} };
class B
{ public:
int y;
void get_data1()
{
cout<< "enter value of y: "; cin>> y;
} };
class C : public A, public B
{
public:
void sum()
{
cout<< "Sum = " << x + y;
}
};
int main()
{
C obj;
obj.get_data();
obj.get_data1();
obj.sum();
return 0;
} //end of program
Output
3. Multilevel Inheritance
If a class is derived from another derived class then it is called multilevel inheritance.
}
Class C : public B
{
//body
}
Example
#include<iostream>
using namespace std;
class A{
public:
int marks;
voidget_data(){
cout<<"Enter Marks";
cin>>marks;
}
};
class B:public A
{
public:
intshow_data(){
cout<<"Entered Marks: " <<marks;
}
};
class C:public B{
};
main(){
C obj;
obj.get_data();
obj.show_data();
}
Output
4. Hierarchical Inheritance
Hierarchical inheritance is a kind of inheritance where more than one class is inherited from a
single parent or base class. Especially those features which are common in the parent class is also
common with the base class.
Example
#include<iostream>
using namespace std;
class A
{
public:
intx,y;
voidget_data()
{
cout<< "Enter value of x: ";
cin>> x;
cout<<"Enter value of y: ";
cin>>y;
}
};
class B:public A
{
public:
voidshow_sum()
{
cout<< "Sum of x and y is : "<<x+y<<endl;
}
};
class C : public A
{
public:
voidshow_product()
{
cout<< "Product of x and y is : "<<x*y;
}
};
int main()
{ B obj1;
C obj2;
obj1.get_data();
obj1.show_sum();
obj2.get_data();
obj2.show_product();
return 0;
}
Output
5. Hybrid Inheritance
There could be situations where we need to apply two or more types of inheritance to design a
program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
Example
#include <iostream>
using namespace std;
class A
{
public:
int x;
};
class B : public A
{
public:
B()
{
x = 500;
}
};
class C
{
public:
int y;
C()
{
y = 100;
}
};
int main()
{
D obj1;
obj1.sum();
return 0;
}
Output
derived class.
3. Protected: C++ provides a third visibility modifier, protected, which serve a little purposein the
inheritance. A member declared as protected is accessible by the member functionswithin its class
and any class immediately derived from it. It cannot be accessed by functionsoutside these two
classes.
Private derivation means that the base class has been inherited privately. Public members and
protected members of the base class are private within the derived class.Private members of the
base class stay private within the base class.
Syntax
classbase_class_name
{
-----
-----
}
// Program
#include<iostream>
using namespace std;
classemp{
private:
int id;
char name[10];
int salary;
voidget_data(){
cout<<"Enter Id,Name and Salary of employee"<<endl;
cin>>id>>name>>salary;
}
public:
voiddisp(){
get_data();
cout<<"Details are"<<endl;
cout<<"Emp ID "<< id<<endl<<"Emp Name " <<name <<endl<<"Emp Salary "<<salary;
}
};
main(){
empobj;
obj.disp();
}
Output
Summary
Inheritance is the capability of one class to inherit properties from another class.
It supports reusability of code and is able to simulate the transitive nature of real lifeobjects.
Inheritance has many forms: Single inheritance, multiple inheritance, hierarchicalinheritance,
multilevel inheritance and hybrid inheritance.
A subclass can derive itself publicly, privately or protected. The derived class constructoris
responsible for invoking the base class constructor, the derived class can directly accessonly the
public and protected members of the base class.
When a class inherits from more than one base class, this is called multiple inheritance.
A class may contain objects of another class inside it. This situation is called nesting of objects and
in such a situation, the contained objects areconstructed first before constructing the objects of the
enclosing class.
Single Inheritance: Where a class inherits from a single base class, it is known as singleinheritance.
Multilevel Inheritance: When the inheritance is such that the class. A serves as a base classfor a
derived class B which is turn serves as a base class for the derived class C. This typeof inheritance is
Multiple Inheritance: A class inherit the attributes of two or more classes. This mechanism is known
Keywords
Abstract Class: A class serving only a base class for other classes and no objects of which are
created.
Base class: A class from which another class inherits. (Also called super class) Containership: The
relationship of two classes such that the objects of a class are enclosed within the other class.
Derived class: A class inheriting properties from another class. (also called sub class).
Inheritance: Capability of one class to inherit properties from another class.
Inheritance Graph: The chain depicting relationship between a base class and derived class.
Visibility Mode: The public, private or protected specifier that controls the visibility and
availability of a member in a class.
Self Assessment
1. Inheritance allow in C++ program?
A. Class Re-usability
B. Creating a hierarchy of classes
C. Extendibility
D. All of above
2. Functions that can be inherited from base class in C++ program.
A. Constructor
B. Destructor
C. Static function
D. None of above
3.
A. Single
B. Multiple
C. Multilevel
D. Hierarchical
6. While inheriting a class, if no access mode is specified, then which among the following is
true in C++?
A. It gets inherited publicly by default
B. It gets inherited protected by default
C. It gets inherited privately by default
D. It is not possible.
11. All the classes must have all the members declared private to implement multilevel
inheritance.
A. True
B. False
C. Sometimes true, sometimes false
D. Always false
14. Which type of inheritance must be used so that the resultant is hybrid?
A. Multiple
B. Hierarchical
C. Multilevel
D. None of the above
15. What is the minimum number of classes to be there in a program implemented hybrid
inheritance?
A. 2
B. 3
C. 4
D. No limit
Review Questions
1. What do you mean by inheritance? Explain different types of inheritance with suitable
example.
2. Consider a situation where three kinds of inheritance are involved. Explain this situation
with an example.
3. What is the difference between protected and private members?
4. Scrutinize the major use of multilevel inheritance.
5. Discuss a situation in which the private derivation will be more appropriate as compared
to public derivation.
6. Write a C++ program to read and display information about employees and managers.
Employee is a class that contains employee number, name, address and department.
Manager class and a list of employees working under a manager.
7. Differentiate between public and private inheritances with suitable examples.
8. Explain how a sub-class may inherit from multiple classes.
9. What is the purpose of virtual base classes?
10. Write a C++ program that demonstrate working of hybrid inheritance.
6. C 7. D 8. C 9. B 10. B
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata McGraw-Hill.
Herbert Schildt; The Complete Reference C++; Tata McGraw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 05: Operator Overloading
Objectives
After studying this unit, you will be able to:
Introduction
C++ comes with a large number of operators. Many of these operators have previously been
defined and used in earlier units. Operator overloading is one of C++'s unique features. In a
programming language that supports object-oriented features, this characteristic is required.
Overloading an operator simply means attaching additional meaning and semantics to an operator.
It enables an operator to exhibit more than one operation polymorphically, as illustrated below:
You're probably aware that the addition operator (+) is primarily a numeric operator, requiring two
number operands. It returns a numeric number equal to the product of the two operands.
Obviously, this can't be used to join two strings together. We may, however, extend the addition
operator's operation to include string concatenation. As a result, the addition operator would work
like this:
This act of redefining the effect of an operator is called operator overloading. The original meaning
and action of the operator however remains as it is. Only an additional meaning is added to it.
Function overloading allows different functions with different argument list having the same name.
Similarly an operator can be redefined to perform additional tasks.
Operator overloading is accomplished using a special function, which can be a member function or
friend function. The general syntax of operator overloading is:
<return_type> operator <operator_being_overloaded>(<argument list>);
To overload the addition operator (+) to concatenate two characters, the following declaration,
which could be either member or friend function, would be needed:
char * operator + (char *s2);
Notes
overloading syntax is quite simple, similar to function overloading, the keyword operator must be
followed by the operator we want to overload:
class Complex
{
public:
Complex(double re,doubleim)
:real(re),imag(im)
{};
Complex operator+(const Complex& other);
Complex operator=(const Complex& other);
private:
double real;
doubleimag;
};
Complex Complex::operator+(const Complex& other)
{
doubleresult_real = real + other.real;
doubleresult_imaginary = imag + other.imag;
return Complex( result_real, result_imaginary );
}
The assignment operator can be overloaded similarly. Notice that we did not have to call any
accessor functions in order to get the real and imaginary parts from the parameter other since the
overloaded operator is a member of the class and has full access to all private data.
Alternatively, we could have defined the addition operator globally and called a member to do the
operators that need the first operand to be assignable, such as : operator=, operator(), operator[]
and operator->, so their use is restricted just as member functions (non-
overloaded globally. The operator=, operator& and operator, (sequencing) have already defined
meanings by default for all objects, but their meanings can be changed by overloading or erased by
making them private.
concatenation:
member
selection (.), and member selection through a pointer to a function(.*). Overloading assumes you
general pointers. The standard behavior of operators for built-in (primitive) types cannot be
will not evaluate all three operations and will stop after a false one is found. This behavior does not
apply to operators that are overloaded by the programmer.
This is due to the use of this technique almost everywhere in the standard library (STL). Actually
the most basic operations in C++ are done with overloaded operators, the IO(input/output)
operators are overloaded versions of shift operators(<<, >>). Their use comes naturally to many
beginning programmers, but their implementation is not straightforward. However a general
format for overloading the input/output operators must be known by any C++ developer. We will
apply this general form to manage the input/output for our Complex class:
friendostream&operator<<(ostream&out, Complex c) //output
{
\
\
return out;
}
friendistream&operator>>(istream&in, Complex &c) //input
{
\
in>>c.real;
\
in>>c.imag;
return in;
}
A important trick that can be seen in this general way of overloading IO is the returning reference
for istream/ostream which is needed in order to use them in a recursive manner:
Complex a(2,3);
Complex b(5.3,6);
cout<<a<<b;
Notes
1. Operators already predefined in the C++ compiler can be only overloaded. Operator cannot
change operator templates that is for example the increment operator ++ is used only as unary
operator. It cannot be used as binary operator.
2. Overloading an operator does not change its basic meaning. For example assume the + operator
can be overloaded to subtract two objects. But the code becomes unreachable.
class integer
{intx, y;
public:
int operator + ();
}
int integer: : operator + ( )
{
return (x-y);
}
3. Unary operators, overloaded by means of a member function, take no explicit argument and
return no explicit values. But, those overloaded by means of a friend function take one reference
argument (the object of the relevant class).
4. Binary operators overloaded through a member function take one explicit argument and those
which are overloaded through a friend function take two explicit arguments.
5. Overloaded operators must either be a non-static class member function or a global function. A
global function that needs access to private or protected class members must be declared as a friend
of that class. A global function must take at least one argument that is of class or enumerated type
or that is a reference to a class or enumerated type.
Example
// Program
#include<iostream>
using namespace std;
class sample{
private:
int x;
public:
sample(){
x=0;
}
void operator ++ (){
++x;
}
voiddisp(){
cout<<"Value of X is"<< x <<endl;
}
};
main(){
sampleobj;
obj.disp();
++obj;
obj.disp();
}
Output
//Program
#include<iostream>
using namespace std;
class Complex{
inta,b;
public:
voidget_data(){
{
cout<< a << "+" << b << "i" << "\n";
}
};
main(){
Complex obj1,obj2,result;
obj1.get_data();
obj1.display();
obj2.get_data();
result=obj1+obj2;
result.display();
}
Output
Notes
A friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class.
//Program
#include <iostream>
Output
3. If the leftmost operand is not a member of the class type, such as when overloadingoperator+(int,
YourClass), or operator<<(ostream&, YourClass), the operator must beoverloaded as a friend.
4. The assignment (=), subscript ([]), call (()), and member selection (->) operators must
beoverloaded as member functions.
class Cents
{
private:
intm_nCents;
public:
Cents(intnCents) { m_nCents = nCents; }
// Overload -cCents
Cents operator-();
};
// note: this function is a member function!
Cents Cents::operator-()
{
return Cents(-m_nCents);
}
Caution: Remember that when C++ sees the function prototype Cents Cents::operator-();,the
compiler internally converts this to Cents operator-(const Cents *this), which you willnote is almost
identical to our friend version Cents operator-(const Cents &cCents)!
You'll notice that this procedure is very similar to the previous one. The member function version
of operator, on the other hand, does not take any parameters! What happened to the parameter?
You learnt that a member function has an implicit *this pointer that always points to the class object
the member function is working on in the course on the hidden this pointer. In the member
function version, the parameter we had to explicitly list in the friend function version (which
doesn't have a *this pointer) becomes the implicit *this parameter.
Most programmers find the friend function version easier to read than the member functionversion,
because the parameters are listed explicitly. Furthermore, the friend function versioncan be used to
overload some things the member function version cannot. For example, friendoperator+(int,
cCents) cannot be converted into a member function because the leftmost parameteris not a class
object.
However, when dealing with operands that modify the class itself (eg. operators =, +=, -=, ++,-,
member functions (such as access functions) to modify private member variables. Writingfriend
functions that modify private member variables of a class is generally not consideredgood coding
style, as it violates encapsulation.
str::str() Notes
{
name = new char[1];
}
str::str(char *a)
{
inti = strlen(a);
name = new char[i + 1];
strcpy(name, a);
}
strstr::operator + (str s)
{
inti = strlen(name) + strlen(s.name);
strtmp;
tmp.name = new char[i+1];
strcpy(tmp.name, name);
strcat(tmp.name, s.name);
returntmp;
}
voidstr::get()
{
cin>> name;
}
voidstr::show()
{
cout<< name;
}
void main()
{
clrscr();
str S3;
S3 = S1 + S2;
S3.show();
}
Summary
In this unit, we have seen how the normal C++ operators can be given new meaningswhen
applied to user-defined data types.
The keyword operator is used to overload an operator, and the resulting operator
willadopt the meaning supplied by the programmer.
Closely related to operator overloading is the issue of type conversion. Some
conversionstake place between user defined types and basic types.
We have seen that how friend function is working with different situations.
Two approaches are used in such conversion: A one argument constructor changes a
basictype to a user defined type, and a conversion operator converts a user-defined type to
abasic type.
When one user-defined type is converted to another, either approach can be used.
Keywords
Operator Overloading: Attaching additional meaning and semantics to an operator. It enablesto
exhibit more than one operations polymorphically.
Strings: The C++ strings library provides the definitions of the basic_string class, which is a
classtemplate specifically designed to manipulate strings of characters of any character type.
Unary Operators: Unary operators operate on one operand (variable or constant). There are
twotypes of unary operators- increment and decrement.
Self Assessment
1. Which is the correct statement about operator overloading in C++?
A. Only arithmetic operators can be overloaded
B. Associativity and precedence of operators does not change
C. Precedence of operators are changed after overloading
D. Only non-arithmetic operators can be overloaded
3.
A. Run time
B. Initial time
C. Compile time
D. Completion time
5.
return no explicit values.
A. Unary operators
B. Binary operators
C. Arithmetic operators
D. Function operator
6. Those operators which operate on two operands or data are called binary operators.
A. True
B. False
#include <iostream>
using namespace std;
class sample {
int x, y;
public:
sample() {}
sample(intsx, intsy) {
x = sx;
y = sy;
} void
show() {
cout<< x << " ";
cout<< y << "\n";
}
friend sample operator+(sample ob1, sample ob2);
};
sample operator+(sample ob1, sample ob2)
{
sample temp;
return temp;
}
int main()
{
sample ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}
A. Overloading function
B. Binary operator overloading using friend function
C. Unary operator overloading
D. None of above
6. A 7. B 8. B 9. A 10. A
Review Questions
1. Overload the addition operator (+) to assign binary addition. The following operationshould be
supported by +.
110010 + 011101 = 1001111
2. Write a program that demonstrate working of binary operator overloading.
3. Which operators are not allowed to be overloaded?
4. What are the differences between overloading a unary operator and that of a binaryoperator?
Illustrate with suitable examples.
5. Why is it necessary to convert one data type to another? Illustrate with suitable examples.
6. How many arguments are required in the definition of an overloaded unary operator?
7. When used in prefix form, what does the overloaded + + operator do differently fromwhat it
does in postfix form?
8. Explain in detail manipulation of strings using operator overloading.
9. Write a note on unary operators.
10. What are the various rules for overloading operators?
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata McGraw-Hill.
Herbert Schildt; The Complete Reference C++; Tata McGraw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 06: Type Conversion
Objectives
After studying this unit, you will be able to:
Introduction
It is the transformation of one type into another. Type casting, in other terms, is the process of
transforming an expression of one type into another.
Conversion of variables from one type to another are known as type conversion. Type conversions
ultimate aim is to make variables of one data type work with variables of another data type.
Type conversions can be used to force the correct type of mathematical computation needed to be
performed.
Depending on whether the type conversion is ordered by the programmer or the compiler, it can be
explicit or implicit. When a programmer wants to go around the compiler's typing system, he or
she uses explicit type conversions (casts); however, the programmer must use them appropriately
to succeed. Problems that the compiler avoids may develop, such as when the processor requires
data of a certain type to be stored at specific addresses or when data is truncated because a data
type on a given platform does not have the same size as the original type. Explicit type conversions
between objects of different kinds result in difficult-to-read code at best.
Example
int a = 45;
float b= 1253.25;
a=b;
This converts float variable b to an integer before its value assigned to a. The type conversion is
automatic as far as data types involved are built in types. We can also use the assignment operator
in case of objects to copy values of all data members of right hand object to the object on left hand.
The objects in this case are of same data type.
Lab Excersise
//Program
#include <iostream>
using namespace std;
int main()
{
int x = 100;
char y = 'a';
x = x + y;
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
Output
Lab Exercise
//Program
#include <iostream>
using namespace std;
int main()
{
double x = 25.5;
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Output
There are three types of situations that arise where data conversion are between incompatible
types. Possible Type Conversions in C++
Example
string s1, s2;
s1 = string(name1);
s2 = name2;
In both the examples, the left-hand operand of = operator is always a class object. Hence, we can
also accomplish this conversion using an overloaded = operator.
Lab exercise
// Program - Using Constructor
#include<iostream>
using namespace std;
class Time
{
int hrs,min;
public:
Time(int t)
{
cout<<"Basic Type to Class Type Conversion...\n";
hrs=t/60;
min=t%60;
}
void show();
};
void Time::show()
{
cout<<hrs<< ": Hours(s)" <<endl;
cout<<min<< " Minutes" <<endl;
}
int main()
{
int duration;
cout<<"\nEnter time duration in minutes";
cin>>duration;
Time t1(duration);
t1.show();
return 0;
}
Output
Lab exercise
// Program - Using Operator
#include<iostream>
using namespace std;
class Time
{
int hrs,min;
public:
void display()
{
cout<<hrs<< ": Hour(s)\n";
cout<<min<<": Minutes\n";
}
void operator =(int t)
{
cout<<"\nBasic Type to Class Type Conversion...\n";
hrs=t/60;
min=t%60;
}
};
int main()
{
Time t1;
int duration;
cout<<"Enter time duration in minutes";
cin>>duration;
cout<<"object t1 overloaded assignment..."<<endl;
t1=duration;
t1.display();
cout<<"object t1 assignment operator 2nd method..."<<endl;
t1.operator=(duration);
t1.display();
return 0;
}
Output
Notes
In this conversion source type is basic type and the destination type is class type.
Basic data type is converted into class type.
In the string example discussed earlier, we can convert the object string to char* as follows:
string::operator char*()
{
retum(str);
}
Lab exercise
// Program
#include<iostream>
using namespace std;
class Time
{
int h,m;
public:
Time(int a,int b)
{
h=a;
m=b;
}
operator int()
{
cout<<"\nClass Type to Basic Type Conversion...";
return(h*60+m);
}
~Time()
{
cout<<"\nDestructor called..."<<endl;
}
};
int main()
{
int h,m,duration;
cout<<"\nEnter Hours ";
cin>>h;
cout<<"\nEnter Minutes ";
cin>>m;
Time t(h,m);
duration = t;
cout<<"\nTotal Minutes are "<<duration;
cout<<"\n2nd method operator overloading ";
duration = t.operator int();
cout<<"\nTotal Minutes are "<<duration;
return 0;
}
Output
Notes
Class type to basic type conversion requires special casting operator function for class type to basic
type conversion. This is known as the conversion function.
Example
Objl = Obj2 ; //Obj1 and Obj2 are objects of different classes.
Obj1 is an object of class one and Obj2 is an object of class two. The class two type data is converted
to class one type data and the converted value is assigned to the Obj1. Since the conversion takes
place from class two to class one, two is known as the source and one is known as the destination
class.
Such conversion between objects of different classes can be carried out by either a constructor or a
conversion function. Which form to use, depends upon where we want the type-conversion
function to be located, whether in the source class or in the destination class.
We studied that the casting operator function
Operator typename()
The following Figure illustrates the above two approaches.
The following Table summarizes all the three conversions. It shows that the conversion from a class
to any other type (or any other class) makes use of a casting operator in the source class. To perform
the conversion from any other type or class to a class type, a constructor is used in the destination
class.
When a conversion using a constructor is performed in the destination class, we must be able to
access the data members of the object sent (by the source class) as an argument.
Lab Exercise
// Program Using Constructor
#include<iostream>
using namespace std;
class Time
{
int hrs,min;
public:
Time(int h,int m)
{
hrs=h;
min=m;
}
Time()
{
cout<<"\n Time's Object Created";
}
int getMinutes()
{
int tot_min = ( hrs * 60 ) + min ;
return tot_min;
}
void display()
{
cout<<"Hours: "<<hrs<<"\n";
cout<<" Minutes : "<<min <<"\n";
}
};
class Minute
{
int min;
public:
Minute()
{
min = 0;
}
void operator=(Time T)
{
min=T.getMinutes();
}
void display()
{
cout<<"\n Total Minutes : " <<min<<"\n";
}
};
int main()
{
Time t1(1,20);
t1.display();
Minute m1;
m1.display();
m1 = t1;
t1.display();
m1.display();
return 0;
}
Output
Lab Exercise
//Program Using conversion function
#include<iostream>
using namespace std;
class inventory1
{
int ino,qty;
float rate;
public:
inventory1(int n,int q,float r)
{
ino=n;
qty=q;
rate=r;
}
int getino()
{
return(ino);
}
float getamt()
{
return(qty*rate);
}
void display()
{
cout<<"\nino = "<<ino<<" qty = "<<qty<<" rate = "<<rate;
}
};
class inventory2
{
int ino;
float amount;
public:
void operator=(inventory1 I)
{
ino=I.getino();
amount=I.getamt();
}
void display()
{
cout<<"\nino = "<<ino<<" amount = "<<amount;
}
};
int main()
{
inventory1 I1(101,50,45);
inventory2 I2;
I2=I1;
I1.display();
I2.display();
}
Summary
A type conversion may either be explicit or implicit, depending on whether it is ordered
by the programmer or by the compiler. Explicit type conversions (casts) are used when a
success in this
endeavour, the programmer must use them correctly.
Used another constructor to build a string type object from a char* type variable.
Which form to use, depends upon where we want the type-conversion function to be
located, whether in the source class or in the destination class.
Keywords
Implicit Conversion: An implicit conversion sequence is the sequence of conversions required to
convert an argument in a function call to the type of the corresponding parameter in a function
declaration.
Explicit Conversion:
Operator Typename(): Converts the class object of which it is a member to typename.
Self Assessment
1. Following program is an example of ___________ conversion.
#include <iostream>
int main()
int x = 100;
char y = 'a';
x = x + y;
float z = x + 1.0;
return 0;
A. Implicit
B. Explicit
C. Both
D. None of Above
D. None of them
6. What will be the data type of the result of the following operation?
(float)a * (int)b / (long)c * (double)d
A. int
B. long
C. float
D. double
9. Which of the following is correct statement for class to basic type conversion?
A. Class type to basic type conversion never performed
B. In this conversion source type is class type and the destination type is basic type.
C. Class type to basic type conversion acts like data type
D. None of above
11. Conversion function must not specify the return value even though it returns the value.
A. True
B. False
12. To convert from a user defined class to a basic type, you would most likely use.
A. Built-in conversion function
B. A one-argument constructor
C.
D.
13. How many ways to perform conversion from one class to another class can perform?
A. 4
B. 2
C. 3
D. 1
14. ____ refers to the process of changing the data type of the value stored in a variable.
A. Type char
B. Type int
C. Type float
D. Type cast
15. Which of the following type-casting have chances for wrap around?
A. From int to float
B. From int to char
C. From char to short
D. From char to int
6. D 7. C 8. D 9. B 10. C
Review Questions
1. What do you mean by type casting? Explain the difference between implicit and explicit
type casting in detail.
2. How type conversion occurs in a program. Explain with suitable example.
3. Write a program that demonstrate working of explicit type conversion.
4. The assignment operations cause automatic type conversion between the operand as per
certain rules. Describe.
5. Write a program that demonstrate working of implicit type conversion.
6. What is class to another class type conversion?
7. List the situations in which we need class type to basic type conversion.
8. How to convert one data type to another data type in C++. Explain in detail.
9. Write a program which the conversion of class type to basic type conversion.
10. There are three types of situations that arise where data conversion are between
incompatible types. What are three situations explain briefly.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 07: Run-time Polymorphism
Objectives
After studying this unit, you will be able to:
Introduction
Polymorphism is a key concept in OOP. Polymorphism refers to the ability to take on multiple
identities. An operation, for example, may behave differently in different situations. The behavior is
determined by the data types utilized in the operation. Take, for example, the addition operation.
For tow numbers, the operation will generate a sum. If the operands are strings, then the operation
will produce a third string by contention. The diagram given below, illustrates that a single
function name can be used to handle different number and types of arguments. This is something
similar to a particular word having several different meanings depending on the context.
Polymorphism is crucial in allowing things with disparate internal structures to share the same
external interface. This means that even while the precise actions associated with each operation
may differ, a generic class of operations can be accessed in the same way. As demonstrated here,
polymorphism is widely used to implement inheritance.
Polymorphism can be implemented using operator and function overloading, where the same
operator and function works differently on different arguments producing different results. These
polymorphisms are brought into effect at compile time itself, hence is known as early binding, static
binding, static linking or compile time polymorphism.
However, uncertainty arises when a function with the same name exists in both the base and
derived classes. Consider the following code snippet as an example.
Class ab
{
Int a;
Public:
Void display(); // display in base class
};
Class ba: public ab
{
Int b;
Public:
Void display(); // display in derived class
};
There is no overloading because the functions ab.display() and ba.display() are the same but in
distinct classes, therefore early binding does not apply. Run time polymorphism selects the right
function at run time.
Example
// Program of runtime polymorphism
#include <iostream>
Output
Lab Exercise
#include<iostream>
using namespace std;
class A{
public:
int x;
};
class B:virtual public A{
public:
int y;
};
class C: virtual public A{
public:
int z;
};
class D:public C,public B{
public:
int x1;
};
main(){
D obj;
obj.x=100;
obj.y=20;
obj.z=30;
obj.x1=200;
cout<< "\n X : "<< obj.x;
cout<< "\n Y : "<< obj.y;
cout<< "\n Z : "<< obj.z;
cout<< "\n X1 : "<< obj.x1;
}
Output
Notes
Lab Exercise
// Program
#include <iostream>
using namespace std;
class A
{
public:
virtual void test() = 0;
};
class B : public A
{
public:
void test()
{
cout << " Hello ! Virtual function " << endl;
}
};
int main(void)
{
B obj;
obj.test();
return 0;
}
Output
Lab Exercise
//Program
#include <iostream>
using namespace std;
class sum
{
int b;
public:
void get_data(int a ){
b=a;
}
int display(){
return b;
}
};
main(){
sum obj;
sum* p;
p=&obj;
p->get_data(10);
cout<<" Value of a "<<p->display();
}
Output
Caution: C++ class is done exactly the same way as a pointer to a structure and to access
members of a pointer to a class access operator (arrow operator) -> is used.
refers to the current instance of the class. If we are going to execute the current instance of the class,
that is the object of my class there and if we have the privilege there using this pointer, we can add
the data into there and we can store some of the information according to that use of this keyword,
it can be used to pass current object as the parameter to the another method, and it can be used to
refer the current class instance variable like we have a class members and their member functions if
we want to use the this pointer there we can access the current members of member functions with
this pointer it can be used to declare the indexes.
Class ABC
{
Int a;
};
a=100;
We can also use the following statement to do the same job:
this->a=100;
Since C++ permits the use of shorthand form a 100, we have not been using the pointer this
explicitly SO far. However, we have been implicitly using the pointer this when overloading the
operators using member function.
Lab Exercise
//Program
#include <iostream>
using namespace std;
class employee
{
int id;
string name;
int salary;
public:
employee(int e_id,string e_name,int e_salary ){
this->id=e_id;
this->name=e_name;
this->salary=e_salary;
}
void display(){
cout<<id<<name<<salary<<endl;
}
};
main(){
employee e1=employee(10,"john",25000);
e1.display();
}
Output
Task:
However, there is a problem in using cptr to access the public members of the derived class D.
Using cptr, we can access only those members which are inherited from B and not the members that
originally belong to D. In case a member of D has the same name as one of the members of B, then
any reference to that member by cptr will always access the base class member.
Although C++ permits a base pointer to point to any object derived from that base, the pointer
cannot be directly used to access all the members of the derived class. We may have to use another
pointer declared as pointer to the derived type.
Lab Exercise
//Program
#include<iostream>
using namespace std;
class base
{
public:
void show()
{
cout<<"Base class"<<endl;
}
};
class derive : public base
{
public:
void display()
{
cout<<"Derived Class";
}
};
int main()
{
base b;
base *bptr;
bptr->show();
derive d;
bptr=&d;
((derive *)bptr)->display();
return 0;
}
Output
Summary
Polymorphism simply means one name having multiple forms.
There are two types of polymorphism, namely, compile time polymorphism and run time
polymorphism.
Functions and operators overloading are examples of compile time polymorphism. The
overloaded member functions are selected for invoking by matching arguments, both type
and number. The compiler knows this information at the compile time and, therefore,
compiler is able to select the appropriate function for a particular call at the compile time
itself. This is called early or static binding or static linking. It means that an object is bound
to its function call at compile time.
In run time polymorphism, an appropriate member function is selected while the program
is running. C++ supports run time polymorphism with the help of virtual functions. It is
called late or dynamic binding because the appropriate function is selected dynamically at
run time. Dynamic binding requires use of pointers to objects and is one of the powerful
features of C++.
Object pointers are useful in creating objects at run time. It can be used to access the public
members of an object, along with an arrow operator.
A this pointer refers to an object that currently invokes a member function. For example,
the function call ashow0 will set the pointer 'this' to the address of the object 'a'.
Pointers to objects of a base class type are compatible with pointers to objects of a derived
class. Therefore, we can use .1 single pointer variable to point to objects of base class as
well as derived classes.
When a function is made virtual, C-+ determines which function to use at run time based
on the type of object pointed to by the base pointer, rather than the type of the pointer. By
making the base pointer to point to different objects, we can execute different versions of
the virtual function.
Run time polymorphism is achieved only when a virtual function is accessed through a
pointer to the base class. It cannot be achieved using object name along with the dot
operator to access virtual function.
Keywords
This Pointer: The pointer is an implicit parameter to all member functions. Therefore, inside a
member function, this may be used to refer to the invoking object.
Abstract Class: A class that contains a pure virtual function is known as an abstract class.
Function Pointer: A function may return a reference or a pointer variable also. A pointer to a
function is the address where the code for the function resides. Pointer to functions can be passed to
functions, returned from functions, stored in arrays and assigned to other pointers.
Memory location: A container that can store a binary number.
Virtual Base Class: Virtual base class is used in situation where a derived have multiple copies of
base class.
Pointer: A variable holding a memory address.
Alias: A different name for a variable of C++ data type. Base Address: Starting address of a
memory location holding array elements.
Reference: An alias for a pointer that does not require de-referencing to use.
Self Assessment
class MyInterface
public:
};
public:
void Display()
int a = 5;
cout << a;
};
public:
void Display()
};
int main()
Class1 obj1;
obj1.Display();
Class2 obj2;
obj2.Display();
return 0;
A. 5
B. 10
C. 15
D. 5 5
7. Which is the pointer which denotes the object calling the member function?
A. Variable pointer
B. This pointer
C. Null pointer
D. Zero pointer
11. Which members can never be accessed in derived class from the base class?
A. Private
B. Protected
C. Public
D. All except private
13. We can access those members of derived class which are inherited from base class by base
class pointer.
A. True
B. False
class base
public:
void show()
cout<<"Base class"<<endl;
};
public:
void display()
cout<<"Derived Class";
};
int main()
base b;
base *bptr;
bptr->show();
derive d;
bptr=&d;
((derive *)bptr)->display();
return 0;
15. If same message is passed to objects of several different classes and all of those can respond
in a different way, what is this feature called?
A. Inheritance
B. Overloading
C. Polymorphism
D. Overriding
6. A 7. B 8. C 9. D 10. A
Review Questions
1. What does polymorphism mean in C++ language?
2. How is polymorphism achieved at run time? Explain with suitable example.
3. What does this pointer point to?
4. What are the applications of this pointer?
5. Write a program that demonstrate working of virtual base class.
6. Why do we need abstract class?
7. What is run time polymorphism?
8. Explain pointer to derived class with suitable example.
9. How does pointer variable differ from simple variable?
10. Write a program that demonstrate the working of abstract class.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 08: Virtual Functions
Objectives
After studying this unit, you will be able to:
Understand concept of binding in C++
Understand early binding and late binding
Demonstrate the virtual functions
Recognize the pure virtual function
Introduction
At compile time, C++ defaults to matching a function call with the correct function definition. This
is referred to as static binding. Dynamic binding allows you to tell the compiler to match a function
call with the correct function definition at runtime. If you use the keyword virtual to declare a
function, the compiler will use dynamic binding for that function.
Virtual functions
In C++ polymorphism refers to the property by which objects belonging to different classes are able
to respond to the same message, but in different forms. An essential requirement of polymorphism
is therefore the ability to refer to objects without any regard to their classes. This necessitates the
use of a single pointer variable to refer to the objects of different classes. Here, we use the pointer to
base class to refer to all the derived objects. But, we just discovered that a base pointer, even when
it is made to contain the address of a derived class, always executes the function in the base class.
The compiler simply ignores the contents of the pointer and chooses the member function that
matches the type of the pointer. How do we then achieve polymorphism? It is achieved using what
is known as 'virtual' functions.
When we use the same function name in both the base and derived classes, the function in base
class is declared as virtual using the keyword virtual preceding its normal declaration. When a
function is made virtual, C++ determines which function to use at run time based on the type of
object pointed to by the base pointer, rather than the type of the pointer. Thus, by making the base
pointer to point to different objects, we can execute different versions of the virtual function.
Notes
A virtual function is a member function which is declared within a base class and is re-
defined (Overridden) by a derived class.
Virtual functions ensure that the correct function is called for an object, regardless of the
type of reference (or pointer) used for function call.
Virtual functions mainly used to achieve run time polymorphism.
Functions are declared with a virtual keyword in base class.
Lab Exercise
//Program
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived d1;
Base* bptr = &d1;
bptr->print();
return 0;
}
Output
Late Binding
Late binding refers to the act of selecting functions while the programme is running. Although late
binding adds to the overhead, it gives you more power and flexibility. Due to the fact that late
binding is implemented using virtual functions, we must specify a class object as either a pointer to
a class or a reference to a class.
For example the following shows how a late binding or run time binding can be carried out
with the help of a virtual function.
class base {
private :
int x;
float y;
public:
virtual void display ( );
int sum ( );
};
class derivedD : public baseA
{
private:
int x;
float y;
public:
void display (); //virtual
int sum ( );
};
void main ( )
{
baseA *ptr;
derivedD objd;
ptr = &objd;
Other Program statements
ptr->display (); //run time binding
ptr->sum ( ); //compile time binding
}
Note that the keyword virtual is be followed by the return type of a member function if a run time
is to be bound. Otherwise, the compile time binding will be effected as usual. In the above program
segment, only the display ( ) function has been declared as virtual in the base class, whereas the
sum () is non-virtual. Even though the message is given from the pointer of the base class to the
objects of the derived class, it will not access the sum ( ) function of the derived class as it has been
declared as non-virtual. The sum ( ) function compiles only the static binding.
The following program demonstrates the run time binding of the member functions of a class. The
same message is given to access the derived class member functions from the array of pointers. As
function are declared as virtual, the C++ compiler invokes the dynamic binding.
#include <iostream.h>
#include <conio.h>
class baseA {
public:
virtual void display () {
\
}
};
class derivedB : public baseA
{
public:
virtual void display 0 {
\
};
class derivedC: public derivedB
{
public:
virtual void display ( ) {
\
};
void main ( ) {
//define three objects
baseA obja;
derivedB objb;
derivedC objc;
base A *ptr [3]; //define an array of pointers to baseA
ptr [0] = &obja;
ptr [1] = &objb;
The following programme demonstrates the static binding of a class's member functions. There are
two classes in the programme: student and academic. The term "class academic" comes from the
term "class student." Both classes have the member functions getdata and display specified. *obj is a
variable for the class student, whose address is recorded in the class academic's object.
# include <iostream.h>
Using namespace std;
class student {
private:
int rollno;
char name [20];
public:
void getdata ( );
void display ( );
};
class academic: public student {
private:
char stream;
public:
void getdata ( );
void display ( );
};
void student:: getdata ( )
{
\
cin>> rollno;
\
cin > > name;
}
void student:: display ( )
{
cout<< endl;
}
void academic :: getdata ()
{
\
cin >>stream;
}
void academic :: display () {
\
cout <<stream<< end!;
}
void main ( )
{
student *ptr;
academic obj;
ptr=&obj;
ptr->getdata ();
ptr->display ();
}
Output
enter rollno
1
enter name
ajay
enter stream of a student?
IT
the
Lab Exercise
#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout << "This is parent class" << endl;
}
};
class Derived : public Base
{
public:
void print()
{
cout << "This is child class" << endl;
}
};
int main()
{
Base *bptr;
Derived d;
bptr= &d;
bptr-> print();
return 0;
}
Output
Early Bindings
Most of the function calls the compiler encounters will be direct function calls. A direct
function call is a statement that directly calls a function.
It is also known as Static Binding or Compile-time Binding.
Direct function calls can be resolved using a process known as early binding.
Early binding (also called static binding) means the compiler is able to directly associate
the identifier name (such as a function or variable name) with a machine address.
All functions have a unique machine address. So when the compiler encounters a function
call, it replaces the function call with a machine language instruction that tells the CPU to
jump to the address of the function.
Example
// Program
#include <iostream>
int main(){
return 0;
Output
Task
Explain the difference between early binding and late binding with suitable programming
examples using C++.
Lab Exercise
#include <iostream>
using namespace std;
class A
{
public:
virtual void test() = 0;
};
class B : public A
{
public:
void test()
{
cout << " Hello ! Pure Virtual function " << endl;
}
};
int main(void)
{
B obj;
obj.test();
return 0;
}
Output
Summary
OOP is used commonly for software development. One major pillar of OOP is
polymorphism. Early Binding and Late Binding are related to that. Early Binding occurs at
compile time while Late Binding occurs at runtime. In method overloading, the bonding
happens using the early binding. In method overriding, the bonding happens using the
late binding. The difference between Early and Late Binding is that Early Binding uses the
class information to resolve method calling while Late Binding uses the object to resolve
method calling.
When a function is made virtual, C-+ determines which function to use at run time based
on the type of object pointed to by the base pointer, rather than the type of the pointer. By
making the base pointer to point to different objects, we can execute different versions of
the virtual function.
If a virtual function is defined in the base class, it need not be necessarily redefined in the
derived class. In such cases, the respective calls will invoke the base class function.
A virtual function, equated to zero is called a pure virtual function. It is a function
declared in a base class that has no definition relative to the base class. A class containing
such pure function is called an abstract class.
Early binding refers to the events that occur at compile time while late binding means
selecting function during the execution. The late binding is implemented through virtual
function.
Keywords
Late Binding: Selecting functions during the execution. Though late binding requires some
overhead it provides increased power and flexibility.
Virtual Function: Virtual functions, one of advanced features of OOP is one that does not really
exist but it appears real in some parts of a program.
Compile time polymorphism: Compile-time polymorphism is achieved through method
overloading.
Run time polymorphism: The runtime polymorphism can be achieved by method overriding.
Do nothing function: The Do-Nothing method is used to arrange that a call to a method or
property should be ignored. When using Do-Nothing, all the logic inside the arranged method or
property body is skipped and nothing happens when you call it.
Self Assessment
4. The prototype of virtual functions should be the same in the base as well as derived class.
A. True
B. False
5.
the derived class.
A. member function
B. virtual function
C. static function
D. real function
6.
the base class.
A. member function
B. virtual function
C. pure virtual function
D. pure function
6. State, whether the following statements about virtual functions are True.
A. i and ii only
B. ii and iii only
C. i and iii only
D. All i, ii and iii
7. State whether the following statements about virtual functions are True or False.
A. True, True
B. True, False
C. False, True
D. False, False
A. early binding
B. static binding
C. static linking
D. All of the above
9.
A. late
B. static
C. dynamic
D. fixed
10. Which of the following concepts means waiting until runtime to determine which function
to call?
A. Data hiding
B. Dynamic loading
C. Dynamic binding
D. Data casting
11. C++ supports run time polymorphism with the help of virtual functions, which is called
A. dynamic
B. run time
C. early binding
D. static
12.
return x+y;
int main(){
int (*fptr)(int,int)=Add;
cout<<fptr(10,40);
return 0;
A. 10
B. 40
C. 50
D. Compile time error
6. C 7. A 8. A 9. D 10. B
Review Questions
1. How can C++ achieve dynamic binding? Explain with suitable example.
2. What do you mean by binding in C++?
3. Differentiate between early binding and late binding.
4. Write a program using C++ that demonstrate working of dynamic binding.
5. Differentiate between virtual function and pure virtual function.
6. Pure virtual functions force the programmer to redefine the virtual function inside the
derived class. Comment the statement.
7. Write a program using C++ that demonstrate working of pure virtual function.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
https://www.codecademy.com/learn/learn-c-plus-plus
http://www.artima.com/cppsource/pure_virtual.html
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101 index.jsp?topic=
%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr142.htm
Objectives
After studying this unit, you will be able to:
Introduction
Many real-life problems handle large volumes of data and, in such situations, we need to use some
devices such as floppy disk or hard disk to store the data. The data is stored in these devices using
the concept of files. A file is a collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these files.
A program typically involves either or both of the following kinds of data communication:
We have already discussed the technique of handling data communication between the console
unit and the program. In this chapter, we will discuss various methods available for storing and
retrieving the data from files.
C++'s I/O system deals with file operations that are quite similar to console input and output
activities. As an interface between the applications and the files, it employs file streams. The input
stream is the one that provides data to the programme, while the output stream is the one that
receives data from the programme. To put it another way, the input stream pulls (or reads) data
from the file, whereas the output stream writes data to the file. Figure shows how this works.
The input operation entails establishing an input stream and connecting it to the programme and
the input file. Similarly, setting up an output stream with the appropriate linkages to the
programme and the output file is part of the output procedure.
Notes
Stream classes in C++ are used to input and output operations on files and i/ o
devices. These classes have specific features and to handle input and output of the
program.
The iostream.h library holds all the stream classes in the C++ programming language.
ofstream: This Stream class signifies the output file stream and is applied to create files for writing
information to files
ifstream: This Stream class signifies the input file stream and is applied for reading information
from files
fstream: This Stream class can be used for both read and write from/to files.
Example
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream st;
st.open("test.txt",ios::out);
if(!st)
{
cout<<"File creation failed";
}
else
{
The pointer is set to the initial location if the file was successfully joined to the stream. The object's
name can be used to access the created file stream. If a path is supplied, the requested file is
searched in that directory; otherwise, the file is only searched in the current directory. If the file isn't
found, a new one is generated in case it's being used for output. If the requested file is identified
while opening a file for output, it is truncated before being opened, resulting in the loss of
everything in the file previously. It is important to guarantee that the application does not
mistakenly overwrite a file. If the file is not discovered, a NULL value is given, which we can check
to make sure we aren't reading a file that isn't there. If we try to read a file that isn't there, we'll get
an error in the application.
ifstream filename;
In this approach the input stream - filename - is created but no specific file is attached to the stream
just created. Once the stream has been created a file can be attached to the stream using open()
member function of the class ifstream or ofstream as is exemplified by the following program
snippet which defines a function to read an input file.
#include <fstream.h>
void read(ifstream &ifstr) // file streams can be passed to functions
{
char ch;
while(!ifstr.eof())
{
ifstr.get(ch);
cout << ch;
}
void main()
{
read(filename);
filename.close();
read(filename);
filename.close();
}
4. Opening Method
The filename is a string of characters that make up a valid filename for the operating system. It may
contain two parts, a primary, name and an optional period with extension. Examples:
Input.data
Test.doc
INVENT.ORY
student
salary
OUTPUT
As stated earlier, for opening a file, we must first create a file stream and then link it to the
filename. A file stream can be defined using the classes ifstream, ofstream, and factream that are
contained in the header file fttream. The class to be used depends upon the purpose, that is,
whether we want to read data from the file or write data to it. A file can be opened in two ways:
As stated earlier, for opening a file, we must first create a file stream and then link it to the
filename. A file stream can be defined using the classes ifstream, ofstream, and fstream that are
contained in the header file fstream. The class to be used depends upon the purpose, that is,
whether we want to read data from the file or write data to it. A file can be opened in two ways:
1. Create a file stream object to manage the stream using the appropriate class. That is to say,
the class ofstream is used to create the output stream and the class ifstream to create the
input stream.
2. Initialize the file object with the desired filename.
For example, the following statement opens a file named "results" for output:
ofstream outfile("results"); // output only
This creates outfile as an ofstream object that manages the output stream. This object can be any
valid C++ name such as o_file, myfile or Pout. This statement also opens the file results and
attaches it to the output stream outfile. This is illustrated in Figure.
Similarly, the following statement declares infile as an ifstream object and attaches it to the file data
for reading (input).
ifstream infile("data"); // input only
The program may contain statements like:
outfile « "TOTAL.;
outfile « sum;
infile » number;
infile >> string;
Lab Exercise
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream of("demo.txt");
of<< "Writing to file using fstream constructor!" << endl;
of.close ();
return 0;
}
Notes: The constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize
file stream objects with the filenames passed to them.
Notes
If the situation requires simultaneous processing of two files, then you need to create a
separate stream for each file.
Lab Exercise
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string text;
ifstream ReadFile("a.txt");
while (getline (ReadFile, text)) {
cout << text;
}
ReadFile.close();
return 0;
}
Lab Exercise
Lab Exercise
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream is("demo.txt");
char c;
while (is.get(c))
cout << c;
if (is.eof())
cout << "EoF reached";
else
cout << "error reading";
is.close();
return 0;
}
Output
Task
Write a program using C++ to demonstrate process of reading from file in C++.
Write a program using C++ to demonstrate process of writing in file.
Summary
The C++ I/O system contains classes such as ifstream, ofstream and fatream to deal with
file handling. These classes are derived from fstreambase class and are declared in a
header file iostream.
A file can be opened in two ways by using the constructor function of the class and using
the member function open() of the class. While opening the file using constructor, we need
to pass the desired filename as a parameter to the constructor.
The open() function can be used to open multiple files that use the same stream object.
The second argument of the open() function called file mode, specifies the purpose for
which the file is opened.
If we do not specify the second argument of the open() function, the default values
specified in the prototype of these class member functions are used while opening the file.
The default values are as follows:
ios :: in for ifstream functions, meaning-open for reading only.
ios :: out for ofstream functions, meaning-open for writing only.
When a file is opened for writing only, a new file is created only if there is no file of that
name. If a file by that name already exists, then its contents are deleted and the file is
presented as a clean file.
To open an existing file for updating without losing its original contents, we need to open
it in an append mode.
The (stream class does not provide a mode by default and therefore we must provide the
mode explicitly when using an object of (stream class. We can specify more than one file
modes using bitwise OR operator while opening a file.
Keywords
ofstream: This Stream class signifies the output file stream and is applied to create files for writing
information to files
ifstream: This Stream class signifies the input file stream and is applied for reading information
from files
fstream: This Stream class can be used for both read and write from/to files.
File: A file is a collection of related data stored in a particular area on the disk.
eof(): It returns non-zero when the end of file has been reached, otherwise it returns zero.
Self Assessment
4. iostream is a subclass of
A. istream
B. instream
C. ostream
D. Both istream and ostream
9. Which of the following is the default mode of the opening using the ofstream class?
A. ios::in
B. ios::trunk
C. ios::out
D. ios::app
10. Which of the following is the default mode of the opening using the fstream class?
A. ios::in| ios::out
B. ios::trunk
C. ios::out
D. ios::in
11.
only with file capable of output.
A. True
B. False
12. The close() function is used to close a file,closed by disconnecting with its streaming.
A. True
B. False
A. myfile@close();
B. myfile.close();
C. myfile:close();
D. myfile$close();
A. Returns true if a file opens for reading has reached the next character.
B. Returns true if a file opens for reading has reached the next word.
C. Returns true if a file opens for reading has reached the end.
D. Returns true if a file opens for reading has reached the middle.
6. A 7. B 8. C 9. C 10. A
Review Questions
1. What do you mean by C++ streams?
2. What are the uses of files in computer system and how data can be write using C++.
3. What are the steps involved in using a file in a C++ program.
4. What is a file mode? Describe the various file mode options available.
5. Describe the various approaches by which we can detect end of file condition successfully.
6. Write a C++ program to demonstrate working of detection of end of file in C++.
7. What are the advantages of files?
8. How can we open a file? Explain with suitable example.
9. Write full process with suitable C++ program for create a new file.
10. Explain file opening process in C++.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://study.com/academy/lesson/practical-application-for-c-plus-plus-programming-
working-with-files.html
https://www.codecademy.com/learn/learn-c-plus-plus
https://www.guru99.com/cpp-file-read-write-open.html
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 10: More on Files
Objectives
After studying this unit, you will be able to:
Introduction
One of the most essential features of interactive programming is its ability to interact with the users
through operator console usually comprising keyboard and monitor. Accordingly, every computer
language (and compiler) provides standard input/output functions and/or methods to facilitate
console operations.
C++ accomplishes input/output operations using concept of stream. A stream is a series of bytes
whose value depends on the variable in which it is stored. This way, C++ is able to treat all the
input and output operations in a uniform manner. Thus, whether it is reading from a file or from
the keyboard, for a C++ program it is simply a stream.
Programs frequently read data from a data file and write the result to another (or the same) data
file. This section will cover concerns with using a C++ programme to access data from a data file.
Concept of Streams
A stream is a source of sequence of bytes. A stream abstracts for input/output devices. It can be
tied up with any I/O device and I/O can be performed in a uniform way. The C++ iostream library
is an object-oriented implementation of this abstraction. It has a source (producer) of flow of bytes
and a sink (consumer) of the bytes. The required classes for the stream I/O are defined in different
library header files.
To use the I/O streams in a C++ program, one must include iostream.h header file in the program.
This file defines the required classes and provides the buffering. Instead of functions, the library
provides operators to carry out the I/O. Two of the Stream Operators are:
Example
#include <iostream> // Header for stream I/O.
int main(void)
{
int x; // variable to hold the input integer
cin >> x;
cout \ x;
}
There are some special functions that can alter the state the stream. These functions are called
manipulators. Stream manipulators are defined in iomanip.h.
A file may be opened for a number of file operations. The corresponding stream must be set with
the intended operation. The different file stream modes are indicated by File Access Flags as listed
below:
\
char ch;
while(!filename.eof())
{
filename.get(ch);
cout << ch;
}
filename.close();
}
The general procedure of writing one character at atime in a file is listed below:
1. Create an output file stream from <fstream.h> header file:
ofstream name_of_output_stream;
2. Open the data file by passing the file name (optionally full name) to this output stream:
Lab Exercise
//Program to write in file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream of("demo.txt");
of<< "Writing to file using fstream constructor!" << endl;
of.close ();
return 0;
}
Lab Exercise
//Program to read from file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string text;
ifstream ReadFile("a.txt");
while (getline (ReadFile, text)) {
cout << text;
}
ReadFile.close();
return 0;
}
Note: - Create a.text file and write something in the file before execute above program.
seekg() function
With one argument:
seekg(k) where k is absolute position from the beginning. The start of the file is byte 0.
The first argument represents an offset from a particular location in the file.
The second specifies the location from which the offset is measured.
tellg() function
Lab Exercise
//Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("details.txt",ios::out);
if(!file){
cout<<"Error";
}
file<<"OOP using C++";
cout<<"current position in file"<<file.tellp()<<endl;
file.close();
file.open("details.txt",ios::in);
if(!file){
cout<"error";
}
while(!file.eof()){
cout<<"Position"<<file.tellg();
file>>ch;
cout<<" Character \" "<<ch<<"\""<<endl;
}
file.close();
}
Output
tellp() function returns the position of pointer then using seekp() function the pointer is
shift back from n position.
Lab Exercise
//Program
#include <iostream>
#include<fstream>
using namespace std;
main(){
ofstream file("details.txt",ios::in);
if(!file){
cout<<"Error";
}
else{
cout<<file.tellp()<<endl;
file<<"Good Programming";
file.seekp(150);
cout<<file.tellp()<<endl;
file<<"Good Programming";
file.close();
}
}
Task
Write a program to demonstrate working of file pointers in C++.
ignore()
This function is used when reading a file to ignore certain number of characters. You can use
seekg() as well for this purpose just to move the pointer up in the file. However, ignore() function
has one advantage over seekg() function. The prototype is of ignore() function is given below.
fstream& ignore( int, char);
Caution
You can specify a delimiter character in ignore() function whence it ignores all the characters up to
the first occurrence of the specified delimiter.
Where int is the count of characters to be ignored and delimiter is the character up to which you
would like to ignore as demonstrated in the following program.
//demonstration of ignore() function
#include <fstream.h>
void main()
{
//Assume that the text contained
myfile.read(Carray,10);
cout << Carray << endl; /
myfile.close();
}
getline()
This function is used to read one line at a time from an input stream until some specified criterion is
met. The prototype is as follows:
getline(Array,Array_size,delimiter);
The stopping criterion can be either specified number of characters (Array_size) or the first
\
wish to stop reading until one of the following happens:
1. You have read 10 characters
myfile.close();
}
peek()
This function returns the ASCII code of the current character from an input file stream very much
like get() function, however, without moving the pointer to the next character. Therefore, any
number of successive call to peek() function will return the ASCII code of same character each time.
To convert the ASCII code (as returned by peek() function use char type cast) as demonstrated in
the following code program.
//Demonstration of peek() function
#include <fstream.h>
void main()
{
char ch;
myfile.get(ch);
myfile.close();
}
putback()
This function returns the last read character, and moves the pointer back. In other words, if you use
get() to read a char and move the pointer to next character, then use putback(), it will show you the
same character, but it will set the pointer to previous character, so the next time you call get() again,
it will again show you the same character as shown in the following program.
//Program demonstrating use of putback() function
#include <fstream.h>
void main()
{
// Assume that the text contained in data
char ch;
myfile.get(ch);
myfile.putback(ch);
myfile.get(ch);
cout << ch << endl; // output will again be
myfile.close();
}
flush()
I/O streams are created and maintained in the RAM. Therefore, when dealing with the output file
stream, the data is not saved in the file as the program enters them. A buffer in the memory holds
the data until the time you close the file or the buffer is full. When you close the file the data is
actually saved in the designated file on the disk. Once the data has been written to the disk the
buffer becomes empty again.
In case you want to force the data be saved even though the buffer is not full without closing the
file you can use the flush() function. A call to flush() function forces the data held in the buffer tobe
saved in the file on the disk and get the buffer empty.
Example
//Program
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char fname[20], ch;
ifstream fin;
cout<<"Enter the name of the file: ";
cin.get(fname, 20);
cin.get(ch);
fin.open(fname, ios::in);
if(!fin)
{
cout<<"Error ";
}
while(fin)
{
fin.get(ch);
cout<<ch;
}
fin.close();
return 0;
}
Output
Lab Exercise
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
ofstream fout;
char ch;
int line=0;
int i;
fout.open("sample.txt", ios::app) ;
if(!fout)
{
cout<<"Error"<<endl;
}
for(i=33; i<128; i++)
{
fout.put((char)(i));
}
fout.close();
ifstream fin;
fin.open("sample.txt", ios::in);
fin.seekg(0);
for(i=33; i<128; i++)
{
fin.get(ch);
cout<<i<<" = ";
cout.put((char)(i));
cout<<"\t";
if(!(i%8))
{
cout<<"\n";
line++;
}
if(line>22)
{
system("PAUSE");
line = 0;
}
}
return 0;
}
Output
Update a File
Updating a file is process of changing values in one or more records of a file.
Random Access
Now we have a file open for reading. By default, the file is open and the cursor is sitting at the
beginning of the file. But now we want to move the file pointer that is the read/write location
inside your file. Note that we told C++ to open the file in append mode. This means our pointer is
now at the END of the file.
Once you have a file open for processing, you can navigate to different parts of the file. This is often
referred to as random access of files. It really means that you aren't at the beginning or the end.
Two functions are available:
Regular Files
Regular files are the most common files. Another name for regular files is ordinary files. Regular
files contain data.
Text Files
Text files are regular files that contain information readable by the user. This information is stored
in ASCII. You can display and print these files. The lines of a text file must not contain NUL
characters, and none can exceed {LINE_MAX} bytes in length, including the new-line character.
The term text file does not prevent the inclusion of control or other nonprintable characters (other
than NUL). Therefore, standard utilities that list text files as inputs or outputs are either able to
process the special characters gracefully or they explicitly describe their limitations within their
individual sections.
Binary Files
Binary files are regular files that contain information readable by the computer. Binary files may be
executable files that instruct the system to accomplish a job. Commands and programs are stored in
executable, binary files. Special compiling programs translate ASCII text into binary code.
The only difference between text and binary files is that text files have lines of less than
{LINE_MAX} bytes, with no NUL characters, each terminated by a new-line character.
their early databases like IMS. After the success of Unix, Ritchie extended the file system concept to
every object in his later operating system developments, such as Plan 9 and Inferno.
Traditional file systems offer facilities to create, move and delete both files and directories. They
lack facilities to create additional links to a
in Unix-like OS), and create bidirectional links to files.
Traditional file systems also offer facilities to truncate, append to, create, move, delete and inplace
modify files. They do not offer facilities to prepend to or truncate from the beginning of a file, let
alone arbitrary insertion into or deletion from a file. The operations provided are highly
asymmetric and lack the generality to be useful in unexpected contexts. For example, interprocess
pipes in Unix have to be implemented outside of the file system because the pipes concept does not
offer truncation from the beginning of files.
Secure access to basic file system operations can be based on a scheme of access control lists or
capabilities. Research has shown access control lists to be difficult to secure properly, which is why
research operating systems tend to use capabilities. Commercial file systems still use access control
lists.
A file system is a method for storing and organizing computer files and the data they contain to
make it easy to find and access them. File systems may use a data storage device such as a hard
disk or CD-ROM and involve maintaining the physical location of the files, they might provide
access to data on a file server by acting as clients for a network protocol (e.g., NFS, SMB, or 9P
clients), or they may be virtual and exist only as an access method for virtual data. More formally, a
file system is a set of abstract data types that are implemented for the storage, hierarchical
organization, manipulation, navigation, access, and retrieval of data.
1. Disk file systems: A disk file system is a file system designed for the storage of files on a
data storage device, most commonly a disk drive, which might be directly or indirectly
connected to the computer. Examples of disk file systems include FAT, FAT32, NTFS, HFS
and HFS+, ext2, ext3, ISO 9660, ODS-5, and UDF. Some disk file systems are journaling file
systems or versioning file systems.
2. Flash file systems: A flash file system is a file system designed for storing files on flash
memory devices. These are becoming more prevalent as the number of mobile devices is
increasing, and the capacity of flash memories catches up with hard drives. While a block
device layer can emulate a disk drive so that a disk file system can be used on a flash
device, this is suboptimal for several reasons:
(a) Erasing blocks: Flash memory blocks have to be explicitly erased before they
can be written to. The time taken to erase blocks can be significant, thus it is
beneficial to erase unused blocks while the device is idle.
(b) Random access: Disk file systems are optimized to avoid disk seeks whenever
possible, due to the high cost of seeking. Flash memory devices impose no seek
latency.
(c) Wear leveling: Flash memory devices tend to wear out when a single block is
repeatedly overwritten; flash file systems are designed to spread out writes
evenly.
Log-structured file systems have all the desirable properties for a flash file system. Such file
systems include JFFS2 and YAFFS.
3. Database file systems: A new concept for file management is the concept of a
databasebased file system. Instead of, or in addition to, hierarchical structured
management, files are identified by their characteristics, like type of file, topic, author, or
similar metadata. Example: dbfs.
4. Transactional file systems: Each disk operation may involve changes to a number of
different files and disk structures. In many cases, these changes are related, meaning that it
is important that they all be executed at the same time. Take for example a bank sending
instruction to the other bank and also update its own records to indicate the transfer has
occurred. If for some reason the computer crashes before it has had a chance to update its
own records, then on reset, there will be no record of the transfer but the bank will be
missing some money.
Transaction processing introduces the guarantee that at any point while it is running, a
transaction can either be finished completely or reverted completely (though not
necessarily both at any given point). This means that if there is a crash or power failure,
after recovery, the stored state will be consistent. (Either the money will be transferred or
5. Network file systems: A network file system is a file system that acts as a client for a
remote file access protocol, providing access to files on a server. Examples of network file
systems include clients for the NFS, SMB protocols, and file-system-like clients for FTP
and WebDAV.
6. Special purpose file systems: A special purpose file system is basically any file system
that is not a disk file system or network file system. This includes systems where the files
are arranged dynamically by software, intended for such purposes as communication
between computer processes or temporary file space.
Special purpose file systems are most commonly used by file-centric operating systems
such as Unix. Examples include the procfs (/proc) file system used by some Unix variants,
which grants access to information about processes and other operating system features.
Binary Files
In binary files, to input and output data with the extraction and insertion operators (<< and >>) and
functions likegetline is not efficient, since we do not need to format any data, and data may not use
the separation codes used by text files to separate elements (like space, newline, etc...). File streams
include two member functions specifically designed to input and output binary data sequentially:
write and read. The first one (write) is a member function of ostream inherited by ofstream. And
read is a member function of istream that is inherited by ifstream. Objects of class fstream have
both members. Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
the address of an array of
bytes where the read data elements are stored or from where the data elements to be written are
taken. The size parameter is an integer value that specifies the number of characters to be read or
written from/to the memory block.
Example
// reading a complete binary file
#include <iostream>
#include <fstream>
using namespace std;
ifstream::pos_type size;
char * memblock;
int main () {
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
delete[] memblock;
}
return 0;
} the complete file content is in memory
argc is an integer Holds the number of arguments on the command line Since the
name of the program always corresponds to the first argument, it is always at
least 1
argv is a pointer to an array of character pointers.
Each character pointer in the argv array corresponds a string containing a command-line argument
argv[0] points the name of the program, argv[1] points to the first argument, argv[2] points to the
second argument and so in
Example
LINUX
UNIX
DOS
Example
WINDOWS OS
MAC OS
UBUNTU (LINUX)
Lab Exercise
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i;
cout<<"Total number of arguments: "<<argc;
for(i=0;i< argc;i++)
{
cout<<endl<< i<<"argument: "<<argv[i];
}
return 0;
}
Output
No argument passed
Summary
Fields in C++ are interpreted as a sequence of or stream of bytes stored on some storage
The read( ) and write( ) functions work in binary mode. The ifstream class is used for
input, ofstream for output and itstream for both input and output.
A data of a file is stored in the form of readable and printable characters then the file is
known as text file. A file contains non-readable characters in binary code then the file is
called binary file.
The function get( ) read and write data respectively. The read( ) and write( ) function read
and write block of binary data. The close( ) function close the stream.
C++ treats each source of input and output uniformly. The abstraction of a data source
and data sink is what is termed as stream. A stream is a data abstraction for input/output
of data to and fro the program.
C++ library provides prefabricated classes for data streaming activities. In C++, the file
stream classes are designed with the idea that a file should simply be viewed as a stream
or array or sequence of bytes.
Keywords
Command Line Parameters: The main functions may be defined not to have any parameter. In
some cases, though, the program is provided with some input values at the line of execution. These
values are known as command line parameter.
File: A storage unit that contains data. A file can be stored either on tape or disk.
Input Stream: The stream that suppliers date to the program is known as input stream.
Output Stream: The stream that receives data from the program is known as output stream.
Stream: A stream is a general name given to a flow of data.
Self Assessment
4. Which function is used in C++ to get the current position of file pointer in a file?
A. tell_p()
B. get_pos()
C. get_p()
D. tell_pos()
6. By default reading pointer is set at the end when file open in ios::app mode.
A. True
B. False
7. The get() and put() functions are capable of handling a single character at a time.
A. True
B. False
8. Which of the following is the correct syntax to read the single character to console in the
C++ language?
A. Read ch()
B. Getline vh()
C. get(ch)
D. Scanf(ch)
9. Which of the following is the correct syntax to read the single character to console in the
C++ language?
A. Print ch()
B. Printtline vh()
C. put(ch)
D. Scanf(ch)
printf(""%d"", argc);
return 0;
A. 0
B. 1
C. error
D. Depends on the compiler
15. What does the second parameter of the main function represent?
A. Number of command line arguments
B. List of command line arguments
C. Dictionary of command line arguments
D. Stack of command line arguments
Review Questions
1. How is C++ able to treat all the input and output operation uniformly?
2. What do you mean by file pointers? Explain in detail.
3. Write a note on read() and write() functions.
4. What is a file? Explain different types of files.
5. How can you achieve random access in C++?
6. Write a program in C++ to create a file.
7. Write a program in C++ that creates a text file, which is an exact copy of a given file.
6. B 7. A 8. C 9. C 10. D
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://study.com/academy/lesson/practical-application-for-c-plus-plus-programming-
working-with-files.html
https://www.codecademy.com/learn/learn-c-plus-plus
https://www.guru99.com/cpp-file-read-write-open.html
Objectives
After studying this unit, you will be able to:
Introduction
One of C++'s most advanced and powerful features is the template. Despite the fact that it was not
included in the original C++ specification, it was introduced several years ago and is now
supported by all recent C++ compilers. It is possible to create generic functions and classes using
templates. The kind of data on which a generic function or class is based. This allows the function
or class to work with a variety of data types without having to explicitly recode specialised versions
for each data type.
A template can be considered as a kind of 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.
Example:
className<int> classObject;
className<double> classObject;
Lab Exercise
#include<iostream>
using namespace std;
template<class T>
class sum{
T num1,num2;
public:
sum(T a, T b){
num1=a;
num2=b;
}
void disp(){
cout<<"Numbers are "<<num1<< " "<<num2<<endl;
cout<<"sum is"<<add()<<endl;
}
T add(){return num1+num2;};
};
main(){
sum<int> sumint(50,50);
sum<float> sumfl(50.25,15.225);
cout<<"Int Result" <<endl;
sumint.disp();
cout<<"Float Result"<<endl;
sumfl.disp();
}
Output
Lab Exercise
Output
Here you can see, the body of each version of the function is identical. The same code has to be
repeated to carry out the same function on different data types. This is a waste of time and effort,
which can be avoided using the template utility provided by C ++.
function are not known in advance and a copy of the function has to be created as and when
necessary. Template functions are using the keyword, template. Templates are blueprints of a
function that can be applied to different data types.
Syntax of Template
Template < class type 1, type 2 ... >
Void function - name ( type 2 parameter 1, type 1 parameter 2 ) {...}
Example
Template < class X >
X min ( X a , X b )
{
return (a < b ) ? a : b ;
}
This list of parameter types is called the formal parameter list of the template, and it cannot be
empty. Each formal parameter consists of the keyword, type name, followed by an identifier. The
identifier can be built-in or user-defined data type, or the identifier type. When the function is
invoked with actual parameters, the identifier type is substituted with the actual type of the
parameter. This allows the use of any data type. The template declaration immediately precedes the
definition of the function for which the template is being defined. The template declaration,
followed by the function definition, constitutes the template definition. The template of the max ( )
function is coded below:
# include < iostream.h >
template < class type >
type max ( type x , type y)
{
return x > y ? x : y ;
}
int main ( )
{
32 F) <,
endl;
return 0 ;
}
Output
max ( 30 , 40 ) : 40
max ( 45.67F, 12 . 32F ) : 45 . 67
In the example, the list of parameters is composed of only one parameter. The next line specifies
that the function takes two arguments and returns a value, all of the defined in the formal
parameter list. See what happens if the following command is issued, keeping in mind the template
definition for max ( ) :
max ( a , b ) ;
in which a and b are integer type variables. When the user invokes max ( ) , using two int values,
works just like the
function int max (int, int) defined earlier, to compare two int values. Similarly, if max ( ) is invoked
on the parameter type passed to the function, is called template instantiation. The template specifies
how individual functions will be constructed, given a set of actual types. The template facility
allows the creation of a blueprint for a function like max ( ).
Example
# include < iostream.h >
template < class type >
type square ( type a)
{
type b;
b= a*a ;
return b.;
}
int main ( )
{
return 0 ;
}
Output
Square ( 25 . 45F) : 1125
Square 90 : 1600
Here is another example of the use of template function. Consider the following classes:
class IRON
{
private :
float density ;
public :
IRON ( ) {density = 8.9 }
Float Density ( ) { return density ;}
};
Lab Exercise
#include <iostream>
using namespace std;
template <typename T>
T add(T num1, T num2) {
return (num1 + num2);
}
int main() {
int result1;
double result2;
result1 = add<int>(50, 100);
cout << "Sum of integers = " << result1 << endl;
result2 = add<double>(10.2, 9.25);
cout << "Sum of double = " << result2 << endl;
return 0;
}
Output
Caution:
Differs for these types, you would use template specialize the template function.
Specialization would consist of instantiating the template definition for a specific data type. So,
when the compiler needs to instantiate the template, it finds a predefined version already existing
and uses it. For example, just after the previous template declaration, you could create a template
specialization for char + like this:
Template e >
Void swap < char > ( char + Ihs , char + rhs )
{
char + tmp = new char [ strlen (Ihs) + 1 ] ;
strcpy ( tmp , Ihs) .;
strcpy ( tmp , Ihs);
Strcpy ( Ihs , rhs) ; Notes
Strcpy ( rhs , tmp ) ;
}
Example
#include<iostream>
#include<string>
using namespace std;
template<class T1,class T2>
void display(T1 x,T2 y)
{
\
}
int main(){
display(858.58, 1024);
return 0;
}
Output
858 ABD
858.58 1024
Notes
Overloading a function template means having different sets of function templates which
differ in their parameter list.
If the function template is with the ordinary template, the name of the function remains
the same but the number of parameters differs.
Example:
#include <iostream>
using namespace std;
template <class T>
void display(T t1)
{
cout << "Display template value: "
<< t1 << "\n";
}
void display(int t1)
{
cout << "With integer argument: "
<< t1 << "\n";
}
int main()
{
display(100);
display(10.2);
display('A');
return 0;
}
Output
Task
Write a program to demonstrate working of function template in C++.
Write a program to demonstrate working of overloading function template in C++.
We have seen that a template can have multiple arguments. It is also possible to use non-type
arguments. That is, in addition to the type argument T, we can also use other arguments such as
strings, function names, constant expressions and built-in types. Consider the following example:
template<class T, int size>
class array I a[size];
{
T a[size]; // automatic array initialization
}
This template supplies the size of the array as an argument. This implies that the size of the array is
known to the compiler at the compile time itself. The arguments must be specified whenever a
template class is created. Example:
Summary
C++ supports a mechanism known as template to implement the concept of generic
programming.
Templates classes may be defined as the layout and operations for an unbounded set of
related classes.
Templates allows us to generate a family of classes or a family of functions to handle
different data types.
Template classes and functions eliminate code duplication for different types and thus
make the program development easier and more manageable.
We can use multiple parameters in both the class templates and function templates. A
specific class created from a class template is called a template class and the process of
creating a template class is known as instantiation. Similarly, a specific function created
from a function template is called a template function.
Like other functions, template functions can be overloaded.
Member functions of a class template must be defined as function templates using the
parameters of the class template.
While template functions and classes are usable for any data type, that would hold true
only, as long as the body of functions or the class is identical throughout.
We may also use non-type parameters such basic or derived data types as arguments
templates.
Keywords
Template: A template function may be defined as an unbounded functions. All the possible
parameters to the function are not known in advance and a copy of the function has to be created as
and when necessary.
Template Classes: Template classes may be defined as the layout and operations for an unbounded
set of related classes.
Function Template: We write a generic function that can be used for different data types. Function
templates are special functions that can operate with generic types.
Generic Programming in C++: Generic programming is a technique where generic types are used
as parameters in algorithms so that they can work for a variety of data types.
Self Assessment
3. What is a template?
A. A template is a formula for creating a generic class
B. A template is used to manipulate the class
C. A template is used for creating the attributes
D. None of the above
5. Which of the following best defines the syntax for template function?
T func(T a)
cout<<a;
Review Questions
1. What is generic programming? How is it implemented in C++?
2. A template can be considered as a kind of macro. Then, what is the difference between
them? Distinguish between overloaded functions and function templates.
3. Distinguish between the terms class template and template class.
4. A class (or function) template is known as a parameterized class (or function). Comment.
5. What are Templates?
6. Define template instantiation.
7. List down the rules for using templates.
8. How can you get a template function instantiated?
9. Define the template class with the explaining program.
10. When can a template function be instantiated?
6. C 7. C 8. D 9. B 10. A
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://www.codecademy.com/learn/learn-c-plus-plus
https://isocpp.org/wiki/faq/templates
https://www.startertutorials.com/blog/generic-programming-cpp.html
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 12: More on Templates
Objectives
After studying this unit, you will be able to:
Introduction
A template can be considered as a kind of 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.
Example
#include<iostream>
using namespace std;
template <typename T>
class base {
protected:
int x=100,y=10;
};
public:
int sum() { return this->x+this->y; }
};
int main() {
derived<int> d;
cout<<"Sum of x and y is"<<d.sum();
return 0;
}
Output
Task: Write a program using C++ that demonstrate working of class template and inheritance.
Example
#include <iostream>
using namespace std;
void tprintf(const char* format)
{
cout << format;
}
template<typename T, typename... Targs>
void tprintf(const char* format, T value, Targs... Fargs)
{
Task: Write a program using C++ that demonstrate working of recursion and template
function.
The image above illustrates that, after the Preprocessing phase, all preprocessor directives are
replaced with C++ code in the source code file. Then, the compilation begins.
Preprocessors are programs that process our source code before compilation.
#include filename
The filename is the name of a standard library (if it is enclosed in ankle brackets <>) or a custom
C++ file (if it is enclosed in double quotes "").
When the compiler encounters the #include directive, it replaces the line with the contents of the
file.
These directives instruct the compiler to conditionally include parts of the source code for
compilation. The following code provides an example:
Example
#include <iostream>
using namespace std;
#define PI 3.142
int main() {
#ifdef PI
cout << "The value of PI is: " << PI << endl;
#else
cout << "PI is not defined!" << endl;
#endif
return 0;
}
Importance of macros
Unless making a basic file you have to write #include, which is a macro that pastes the
text contained in a file.
With a name that gives the statement a meaning, its easier to understand the macro than
the lengthy code behind it.
Example
#include<iostream>
using namespace std;
#define END 10
int main(){
int i;
for(i=0;i<=END;i++){
cout<<i<<endl;
}
return 0;
}
Output
Example
//Program Macro as Function
#include <iostream>
using namespace std;
#define MIN(a,b) (((a)<(b)) ? a : b)
int main () {
int i, j;
cout<<"Enter Two numbers";
cin>>i>>j;
cout <<"The minimum is " << MIN(i, j) << endl;
return 0;
}
Output
Summary
C++ supports a mechanism known as template to implement the concept of generic
programming.
Templates classes may be defined as the layout and operations for an unbounded set of
related classes.
Templates allows us to generate a family of classes or a family of functions to handle
different data types.
Macros are a piece of code in a program which is given some name. Whenever this name
is encountered by the compiler the compiler replaces the name with the actual piece of
code. The '#define' directive is used to define a macro.
Template classes and functions eliminate code duplication for different types and thus
make the program development easier and more manageable.
Keywords
Template: A template function may be defined as an unbounded functions. All the possible
parameters to the function are not known in advance and a copy of the function has to be created as
and when necessary.
Template Classes: Template classes may be defined as the layout and operations for an unbounded
set of related classes.
Function Template: We write a generic function that can be used for different data types. Function
templates are special functions that can operate with generic types.
Generic Programming in C++: Generic programming is a technique where generic types are used
as parameters in algorithms so that they can work for a variety of data types.
Preprocessor in C++: As the name suggests Preprocessors are programs that process our source
code before compilation. There are a number of steps involved between writing a program and
executing a program in C / C++.
Self Assessment
3. The same template is used to generate many different instances, this can be done by
A. Functions
B. Template parameters
C. Operators
D. None of them
7. Which is the most significant feature that arises by using template classes?
A. Code readability
B. Ease in coding
C. Code reusability
D. Modularity in code
class base {
protected:
int x=10,y=10;
};
public:
};
int main() {
derived<int> d;
return 0;
A. 10 10
B. 110
C. 20
D. 10
A. $
B. %
C. *
D. #
int main ()
float i, j;
i = 10.1;
j = 10.01;
return 0;
A. 10.01
B. 10.1
C. compile time error
D. none of the mentioned
int main () {
int i, j;
i=90;
j=10;
return 0;
A. The minimum is 0
B. The minimum is 10
C. The minimum is 90
D. Compile time error
Review Questions
1. What is macro? How is it implemented in C++?
2. A template can be considered as a kind of macro. Then, what is the difference between
them? Distinguish between overloaded functions and function templates.
3. How to implement recursion using template in C++.
4. A macro can be used as a function. Comment.
5. What are Templates?
6. Define preprocessor in C++.
7. Differentiate between macro and template.
8. Explain recursion with template function with suitable example
9. Write a program in C++ that demonstrate working of preprocessor in C++.
10. Write a program in C++ that demonstrate working of macro.
6. D 7. C 8. A 9. C 10. C
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://www.codecademy.com/learn/learn-c-plus-plus
https://isocpp.org/wiki/faq/templates
https://www.startertutorials.com/blog/generic-programming-cpp.html
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 13: Exception Handling
Objectives
After studying this unit, you will be able to:
Introduction
We know that it is very rare that a program works correctly first time. It might have bugs. The two
most common types of bugs are logic errors and syntactic errors. The logic errors occur due to poor
understanding of the problem and solution procedure. The syntactic errors arise due to poor
understanding of the language itself. We can detect these errors by using exhaustive debugging
and testing procedures.
We often come across some peculiar exceptions problems other than logic or syntax errors. They are
known as exceptions. Exceptions are run time anomalies or unusual conditions that a program may
encounter while executing. Anomalies might include conditions such as division by zero, access to
an array outside of its bounds, or running out of memory or disk space. When a program
encounters an exceptional condition, it is important that it is identified and dealt with effectively.
ANSI C++ provides built-in language features to detect and handle exceptions which are basically
run time errors.
Exception handling was not part of the original C++. It is a new feature added to ANSI C++. Today,
almost all compilers support this feature. C++ exception handling provides a type-safe, integrated
approach, for coping with the unusual predictable problems that arise while executing a program.
Description is here
std::exception
1
An exception and parent class of all the standard C++ exceptions.
std::bad_alloc
2
This can be thrown by new.
std::bad_cast
3
This can be thrown by dynamic_cast.
std::bad_exception
4
This is useful device to handle unexpected exceptions in a C++ program.
std::bad_typeid
5
This can be thrown by typeid.
std::logic_error
6
An exception that theoretically can be detected by reading the code.
std::domain_error
7
This is an exception thrown when a mathematically invalid domain is used.
std::invalid_argument
8
This is thrown due to invalid arguments.
std::length_error
9
This is thrown when a too big std::string is created.
std::out_of_range
10 This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
std::runtime_error
11
An exception that theoretically cannot be detected by reading the code.
std::overflow_error
12
This is thrown if a mathematical overflow occurs.
std::range_error
13
This is occurred when you try to store a value which is out of range.
std::underflow_error
14
This is thrown if a mathematical underflow occurs.
The catch block that catches an exception must immediately follow the try block that throws the
exception. The general form of these two blocks are as follows:
try
{
}
catch(type org) { // Catches exception
// Block of statements that
// handles the exception
}
When the try block throws an exception, the program control leaves the try block and enters the
catch statement of the catch block. Note that exceptions are objects used to transmit information
about a problem. If the type of object thrown matches the arg type in the catch statement, then catch
block is executed for handling the exception. If they do not match, the program is aborted with the
help of the abort() function which is invoked by default. When no exception is detected and
thrown, the control goes to the statement immediately after the catch block. That is, the catch block
is skipped. This simple try-catch mechanism is illustrated in Program.
#include <iostream>
using namespace std;
int main () {
int x;
cout<<"Enter number";
cin>>x;
try {
if (x >=1) {
cout << "Input is valid";
} else {
throw (x);
}
}
catch (int num) {
cout << "Input Invalid\n";
cout << "Number is: " << num;
}
}
Output
Note
Exception Handling in C++ is a process to handle runtime errors.
A C++ exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
2. Propagating Errors Up the Call Stack: - A second advantage of exceptions is the ability to
propagate error reporting up the call stack of methods.
3. Grouping and Differentiating Error Types: - Because all exceptions thrown within a
program are objects, the grouping or categorizing of exceptions is a natural outcome of the
class hierarchy.
Task: Write a program to demonstrate working of try, throw and catch blocks in C++.
try
{ // try block
catch(type1 arg)
// catch block1
} catch(type2 arg) {
// catch block2
catch(typeN arg) {
// catch blockN
}
Note
Each catch block catches one type of exceptions
Need multiple catch blocks
When the value is not important, the parameter can be omitted.
Lab Exercise
//Program
#include<iostream>
using namespace std;
class compareAges{
public:
int fathersAge;
int sonsAge;
void inputAge(){
cout<<"Enter Fathers Age";
cin>>fathersAge;
cout<<"Enter Sons Age";
cin>>sonsAge;
}
void compare(){
try{
if(fathersAge==sonsAge) throw 55;
else if(sonsAge>fathersAge) throw ('x');
else throw (2.1f);
}
catch(int a){
cout<<"Invalid..";
}
catch(char b){
cout<<"Age of son is never greater than the age of father";
}
catch (float c){
cout<<"Valid input";
}
}
};
main(){
compareAges obj;
obj.inputAge();
obj.compare();
}
Output
Lab Exercise
#include<iostream>
int main()
{
int a=10, b=0, c;
try
{
//if a is divided by b(which has a value 0);
if(b==0)
throw(c);
else
c=a/b;
}
catch(char c) //catch block to handle/catch exception
{
cout<<"Caught exception : char type ";
}
catch(int i) //catch block to handle/catch exception
{
cout<<"Caught exception : int type ";
}
catch(short s) //catch block to handle/catch exception
{
cout<<"Caught exception : short type ";
}
cout<<"\n Hello World";
}
Output
Summary
A try block may throw an exception directly or invoke a function that throws an
exception. Irrespective of location of the throw point, the catch block is placed
immediately after the try block.
We can place two or more catch blocks together to catch and handle multiple types of
exceptions thrown by a try block.
It is also possible to make a catch statement to catch all types of exceptions using ellipses
as its argument.
We may also restrict a function to throw only a set of specified exceptions by adding a
throw specification clause to the function definition.
Keywords
Error - Error is an illegal operation performed by the user which results in abnormal working of the
program.
Exception An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program is running, such
as an attempt to divide by zero.
Run time error - They are also known as exceptions. An exception caught during run time creates
serious issues.
Throw- when a program encounters a problem, it throws an exception. The throw keyword helps
the program perform the throw.
Catch- a program uses an exception handler to catch an exception. It is added to the section of a
program where you need to handle the problem. It's done using the catch keyword.
Try- the try block identifies the code block for which certain exceptions will be activated. It should
be followed by one/more catch blocks.
Self Assessment
13. Generic catch handler must be placed at the end of all the catch handlers.
A. True
B. False
6. A 7. B 8. B 9. A 10. A
Review Questions
1. What do you mean by an error?
2. What is an exception? How it is different from error.
3. What is an exception?
4. How is an exception handle in C++?
5. List the advantages of exception handling.
6. What are the basic implementations of exception handling?
7.
8. When do we use multiple cache statements?
9. What are main keywords that responsible for exception handling in C++.
10. What should we place inside the catch block?
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://study.com/academy/lesson/practical-application-for-c-plus-plus-programming-
https://www.codecademy.com/learn/learn-c-plus-plus
https://www.guru99.com/cpp-file-read-write-open.html
Dr. Prikshat Kumar Angra, Lovely Professional UniversityUnit 14: More on Exception Handling
Objectives
After studying this unit, you will be able to:
Introduction
We know that it is very rare that a program works correctly first time. It might have bugs. The two
most common types of bugs are logic errors and syntactic errors. The logic errors occur due to poor
understanding of the problem and solution procedure. The syntactic errors arise due to poor
understanding of the language itself. We can detect these errors by using exhaustive debugging
and testing procedures.
We often come across some peculiar exceptions problems other than logic or syntax errors. They are
known as exceptions. Exceptions are run time anomalies or unusual conditions that a program may
encounter while executing. Anomalies might include conditions such as division by zero, access to
an array outside of its bounds, or running out of memory or disk space. When a program
encounters an exceptional condition, it is important that it is identified and dealt with effectively.
ANSI C++ provides built-in language features to detect and handle exceptions which are basically
run time errors.
Exception handling was not part of the original C++. It is a new feature added to ANSI C++. Today,
almost all compilers support this feature. C++ exception handling provides a type-safe, integrated
approach, for coping with the unusual predictable problems that arise while executing a program.
Exception Description
Lab exercise
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//Other errors
}
}
Lab exercise
//Program - exception of type bad_typeid
#include <iostream>
#include <exception>
#include <typeinfo>
using namespace std;
class A {virtual fun() {}; };
int main () {
try {
A * a = NULL;
typeid (*a);
}
catch (exception& e)
{
cout << "Exception: " << e.what();
}
return 0;
}
Output
If a catch block cannot handle the particular exception it has caught, we can rethrow the
exception.
The rethrow expression causes the originally thrown object to be rethrown.
Lab exercise
//Program rethrowing exception
#include <iostream>
using namespace std;
int main()
{
try
{
int a, b;
cout<<"Enter two integer values: ";
cin>>a>>b;
try
{
if(b == 0)
{
throw b;
}
else
{
cout<<"Division of a and b is "<<(a/b);
}
}
catch(...)
{
throw;
}
}
catch(int)
{
cout<<"Second value cannot be zero";
}
return 0;
}
Output
Run 1
Run 2
Lab exercise
//Program
#include<iostream>
using namespace std;
class Divide
{
private:
int *x;
int *y;
public:
Divide()
{
x = new int();
y = new int();
cout<<"Enter two numbers: ";
cin>>*x>>*y;
try
{
if(*y == 0)
{
throw *x;
}
}
catch(int)
{
delete x;
delete y;
cout<<"Second number cannot be zero!"<<endl;
throw;
}
}
~Divide()
{
try
{
delete x;
delete y;
}
catch(...)
{
cout<<"Error while deallocating memory"<<endl;
}
}
float division()
{
return (float)*x / *y;
}
};
int main()
{
try
{
Divide d;
float res = d.division();
cout<<"Result of division is: "<<res;
}
catch(...)
{
cout<<"Unkown exception!"<<endl;
}
return 0;
}
Output
Run 1
Run 2
The exception handling subsystem calls the function: unexpected°. This function, provided
by the default C++ library, defines the behavior when an uncaught exception arises. By
default, unexpected calls terminate°.
The terminate function defines the actions that are to be performed during process
termination. This, by default, calls abort0.
Lab exercise
// Program
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;
void myterminate O {
cerr << "terminate handler called\n";
abort();
}
int main (void) {
set_terminate(myterminate);
throw 0;
return 0;
}
Output
Summary
A try block may throw an exception directly or invoke a function that throws an exception.
Irrespective of location of the throw point, the catch block is placed immediately after the try
block.
We can place two or more catch blocks together to catch and handle multiple types of
exceptions thrown by a try block.
It is also possible to make a catch statement to catch all types of exceptions using ellipses as
its argument.
We may also restrict a function to throw only a set of specified exceptions by adding a throw
specification clause to the function definition.
Keywords
Error - Error is an illegal operation performed by the user which results in abnormal working of the
program.