Professional Documents
Culture Documents
C++ All Modules
C++ All Modules
Introduction to C++
1.1: Limitations of C
1. Difficult to debug the errors.
2. ‘C’ compilers can only identify errors & cannot handle runtime errors.
3. It doesn’t provide data protection.
4. It does not exhibit namespace property.
5. It also doesn’t feature the reusability of source code extensively.
6. ‘C’ language prevents & prohibits the concepts of ‘OOP’ language.
7. C programming has an insufficient level for data abstraction, i.e., does not
have very large data handling capacity.
8. It doesn’t provide strict datatype checking.
9. It does not support solving real-world problems.
10. C Language does not allow the user to detect the errors with the help of
exception handling features.
11. C is frequently used in small and medium-sized programs.
No. C C++
2) Data is less secured in C. In C++, you can use access modifiers for
class members to make it inaccessible
for outside users.
7) In C, scanf() and printf() are C++ mainly uses stream cin and cout to
mainly used for input/output. perform input and output operations.
10) Exception handling is not easy in C++ provides exception handling using
C. It has to perform using other Try and Catch block.
functions.
Understanding.
Maintenance.
Evolution.
Main function
Function 1 Function 4
Function 2 Function 3
1.7.1: TYPICAL STRUCTURE OF POP:
POP basically consists of writing a list of instructions for the computer to follow &
organize these instructions into groups known as functions.
Dividing a program into functions leads to structured programming.
Structured programming is not very efficient for large programs.
The relationship between functions and data is as shown below:
Global data1 Global data2
CHARACTERISTICS/ADVANTAGES OF POP:
1. Emphasis is on doing algorithms.
2. Large programs are divided into smaller programs known as functions.
3. Most of the functions share global data.
4. Data move openly around the system from function to function.
5. Functions transform data from one from to another.
6. Employs top-down approach in approach in program design.
DISADVANTAGES OF POP:
For large programs complexity and cost will be high.
Data is not secure.
POP is difficult to design because the main components of procedural programs
are functions and data structures.
Procedural languages are not usually extensible i.e., creation of new data type is
difficult.
Object-A Object -B
Data Data
Functions Functions
ADVANTAGES OF OOP:
1. Emphasis is on data rather than procedure.
2. Programs are divided into objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of the object are tied together in the data
structure.
OBJECTS:
Objects are the basic runtime entities in an object-oriented system.
Object is a collection of variables that hold the data & functions that operate on
the data.
Variables can be accessed using objects are called data members.
Functions that can be accessed using objects are called member functions.
So, object=data member+member functions.
Pictorially object looks like as follows:
Object
Data-1 data members
Data-2 (variables)
--------
--------
Function-1 member functions
Function-2
CLASSES:
Class is a collection of objects having common features.
Classes are user-defined data types & behave like the built-in data-types.
Objects are variables of type class.
Once a class is been defined, we can create any number of objects belonging to that
class.
Ex: If fruit is a class, then mango, apple, orange etc are objects of class fruit.
fruit mango;
INHERITANCE:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
It supports hierarchical classification.
The concept of inheritance provides the idea of reusability. This means we can add
additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one.
Hierarchical classification is as shown below:
Bird
Attributes
--------------
Flying birds Non-flying birds
Attributes Attributes
------------- - -----------
Robin Swallow Penguin Kiwi
Attributes Attributes Attributes Attributes
------------ ------------ ------------ ------------
Shape
(draw)
Example 3:
Just like the arithmetic addition operator, it is possible to cascade the ‘insertion’ operator.
#include<iostream.h>
#include<conio.h>
void main()
{
int x=10;
float y=2.2;
clrscr();
cout<<x<<endl<<y; //cascading the insertion operator
getch();
}
OUTPUT:
10
2.2
Example 4:It is needless to say that we can pass constants instead of variables as operands
to the ‘insertion’ operator.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<10<<endl<< ”Hello \n”<<3.4; //cascading the insertion operator
getch();
}
Output:
10
Hello
3.4
Example 5:
# include <iostream.h>
void main ( )
{
int x, y; Output: 10
x=10; 20
y=20;
cout<<x;
cout<<endl;
cout<< y;
}
Example 6:
# include <iostream.h>
void main ( )
{
int a=10; Output: 10
float b=10.5; 10.5
char d=’a’; a
cout<<a<<b<<d;
}
# include <iostream.h>
void main ( )
{
int x;
cout<<”enter a number”;
cin>>x;
cout<<x;
}
Output:
Enter a number
20
20
Example 2:
Just like the ‘insertion’ operator, it is possible to cascade the ‘extraction’ operator.
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
cout<<“Enter a two number: “;
cin>>x>>y;
cout<<“The entered numbers is:”<<x<<“ and “<<y;
getch();
}
Output:
...
};
Why structs in C?
Suppose you want to store information about a person: his/her name, citizenship number,
and salary. You can create different variables name, citNo and salary to store this information.
What if you need to store information of more than one person? Now, you need to create
different variables for each information per person: name1, citNo1, salary1, name2, citNo2,
salary2, etc. A better approach would be to have a collection of all related information under
a single name Person structure and use it for every person.
Example:
#include <stdio.h>
#include <string.h>
int main() {
person1.citNo = 1984;
person1. salary = 2500;
return 0;
}
Everything in C++ is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These
are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Struct Class
struct person class person
{ {
float salary; float salary;
char name[20]; char name[20];
} int display()
{
cout<<”Hello”;
}
}
“The data members and member functions” of class can be accessed using the dot(‘.’)
operator with the object. For example if the name of object is obj and you want to access the
member function with the name printName() then you will have to write obj.printName() .
int main() {
MyClass myObj; // Create an object of MyClass
int main() {
int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Data Abstraction
Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation.
o C++ provides a great level of abstraction. For example, pow() function is used to
calculate the power of a number without knowing the algorithm the function follows.
o Let's take a real life example of AC, which can be turned ON or OFF, change the
temperature, change the mode, and other external components such as fan, swing.
But, we don't know the internal details of the AC, i.e., how it works internally.
#include <iostream>
using namespace std;
class implementAbstraction {
private:
int a, b;
public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}
void display()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
o Interface
o Abstract class
A Pure Virtual Function is a function where we only declare the function but not the function
definition. The implementation for pure virtual methods is done at the derived class by
method/function overriding.
Importance of Interfaces:
o Any class derived from the pure abstract class (Interface) must implement all of the
methods of the base class i.e. Interface.
o Interface pointers can be passed to functions and classes thereby we can call the
functions of the derived class from there itself.
o We can create a pointer to the instance of the derived class with a reference of a base
abstract class.
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Rectangle : Shape
{
public:
void draw()
{
cout < <"drawing rectangle..." < <endl;
}
};
class Circle : Shape
{
public:
void draw()
{
cout <<"drawing circle..." < <endl;
}
};
int main( ) {
Rectangle rec;
Circle cir;
rec.draw();
cir.draw();
return 0;
}
Abstract class
Data Abstraction is a programming technique that depends on the separation of the interface
and implementation details of the program.
Data
Abstraction
o Public specifier: When the members are declared as public, members can be accessed
anywhere from the program.
o Private specifier: When the members are declared as private, members can only be
accessed only by the member functions of the class.
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}
Encapsulation
1. The wrapping up of data and functions into a single unit (called class) is known as
Encapsulation.
2. It hides the implementation details of an object from its users.
3. Encapsulation prevents unauthorized access of data or functionality.
4. The data is not accessible to the outside world, and only functions which are wrapped
in the class can access it.
5. This is called data hiding or information hiding.
Inheritance
1. Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
2. Hierarchical Classification
3. Reusability – adding additional features to an existing class without modifying it.
4. That is, deriving a new class from the existing one.
5. The new class will have the combined features of both the classes.
6. New class is also called as Derived class and existing class is called as Base Class.
Polymorphism
Ability to take more than one form. The polymorphism is an ability to access different
implementations of a function using the same name.
Ex: Function to perform addition operation
Operator Overloading: The process of making an operator to exhibit different behaviours in
different instances.
Function Overloading: Using a single function name to perform different types of tasks.
Example:
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
cout<<d.color;
}
Dynamic Binding
Dynamic binding (late binding) means that the code associated with a procedure call is
not known until the time of the call at run-time.
Usually associated with Polymorphism and Inheritance.
At run-time, the code matching the object under current reference will be called.
C++ Tokens
Each word and punctuation is referred to as a token in C++. Tokens are the smallest
building block or smallest unit of a C++ program.
Identifiers
Keywords
Constants
Operators
Strings
Identifiers: Identifiers are names given to various entries, such as variables, structures,
and functions. Also, identifier names must be unique as these entities are used in
program execution.
Keywords: Keywords are reserved words with fixed meanings that cannot be changed.
The meaning and working of these keywords are already known to the compiler. Eg:
namespace, public, inline, bool.
Constants: Constants are like a variable, except that their value never changes during
execution once defined. Constants often represent fixed values used frequently in the
code. Eg: const double PI = 3.14159;
Operators: In C++, operators are special symbols that are used to perform operations
on one or more operands. An operand is a value on which an operator acts. C++ has a
wide range of operators, including arithmetic operators, relational operators, logical
operators, and others.
Strings: Strings are objects that signify sequences of characters which is enclosed inside the
double quotes.
Char string-name[size];
The scope resolution operator is used to reference the global variable or member
function that is out of scope. Therefore, we use the scope resolution operator to
access the hidden variable or function of a program. The operator is represented as
the double colon (::) symbol.
Example 1:
#include <iostream>
using namespace std;
int num = 50;
int main ()
{
int num = 100;
cout << " The value of the local variable num: " << num; O/P:100
// use scope resolution operator (::) to access the global variable
cout << "\n The value of the global variable num: " <<: :num; O/P:50
return 0;
}
#include <iostream>
using namespace std;
class Operate
{
public:
void fun();
};
// define the member function outside the class.
void Operate::fun() /* return_type Class_Name::function_name */
{
cout << " It is the member function of the class. ";
}
int main ()
{
// create an object of the class Operate
Operate op;
op.fun();
return 0;
}
Expression and their types
An expression can be a combination of other expressions; while computation, first inner
expressions are calculated, then the overall expression. A function call that returns
some value could be part of an expression.
• Integral expressions: The expressions that produce an integer value as output after
performing all types of conversions are called integral expressions. For example, x, 6*x-
y and 10 +int (5.0) are integral expressions. Here, x and yare variables of type into
• Float expressions: The expressions that produce floating-point value as output after
performing all types of conversions are called float expressions. For example, 9.25, x-y
and 9+ float (7) are float expressions. Here, x ‘and yare variables of type float.
• Relational or Boolean expressions: The expressions that produce a bool type value,
that is, either true or false are called relational or Boolean expressions. For example, x +
y<100, m + n==a-b and a>=b + c. are relational expressions.
• Logical expressions: The expressions that produce a bool type value after combining
two or more relational expressions are called logical expressions. For example, x==5
&&m==5 and y>x I I m<=n are logical expressions.
• Bitwise expressions: The expressions which manipulate data at bit level are called
bitwise expressions. For example, a >> 4 and b<< 2 are bitwise expressions.
• Pointer expressions: The expressions that give address values as output are
called pointer expressions. For example, &x, ptr and -ptr are pointer expressions. Here,
x is a variable of any type and ptr is a pointer.
a = (b=20); or a=b=20;
int a=b=30; // illegal
int a=30, int b=30; //valid
Function prototype
A function prototype describes the function interface to the compiler by giving details
such as the number and type of arguments and the type of return values.
The prototype declaration looks just like a function definition except that it has no body
i.e., its code is missing. This is the time you knew the difference between a declaration
and a definition.
Example:
Int main()
Int a=10,b=20,c;
c = add(a,b);
cout<<”Add”<<c;
Int z;
z=x+y;
returnz;
Call by reference
1. Call by Reference is a method in which it passes the reference or address of the
actual parameter to the function's formal parameters, which means if there is
any change in the values inside the function, it reflects that change in the actual
values.
2. If there is any change in the values inside the function, it reflects that change in
the actual values.
Example:
void increment(int s)
{
s=s+5000;
cout<<”After increment\n”;
}
Int main()
{
Int sal;
Prof. Supriya C, Dept. of ISE,AIT 5
Lecture Notes Module 2 Functions in C++
sal=50000;
increment(sal);
cout<<”Before incerement”<<sal;
return 0;
}
Return by reference
Return a value by reference
#include <iostream>
using namespace std;
int num;
int& test();
int main()
{
test() = 5;
cout << num;
return 0;
}
int& test() {
return num;
}
Note : test() =”return type of function” is int&
Int& test()
{ return 2; }
Int &test()
Inline Functions
When an instruction of a function call is encountered during the compilation of a program, its
memory address is stored by the compiler. The function arguments are copied on the stack and
after the execution of the code, the control is transferred to the calling instruction.
After the execution of the code , the controlled transferred to the calling function.
In case of inline functions, the compiler does not go through the above process of switching
between the stack and calling function. Instead, it copies the definition of the inline function
and the calling instruction with that definition.
When the function is small, execution time is lesser than the switching time.
Example:
Default Arguments
If a function with default arguments is called without passing arguments, then the default
parameters are used.
We can understand the working of default arguments from the image above:
1. When temp() is called, both the default parameters are used by the function.
2. When temp(6) is called, the first argument becomes 6 while the default value is
used for the second parameter.
3. When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3.
4. When temp(3.4) is passed, the function behaves in an undesired way because
the second argument cannot be passed without passing the first argument.
Therefore, 3.4 is passed as the first argument. Since the first argument has been
defined as int, the value that is actually passed is 3.
Function Overloading
These functions having the same name but different arguments are known as
overloaded functions.
Examples
int test() { }
int test(int a) { }
float test(double a) { }
Class Moverlaod
{
Int add (int a , int b)
{
Int sum=a+b;
return sum;
}
Int add (int a , int b,int c)
{
Int sum=a+b+c;
return sum;
}
float add(float a,float b)
{
Float a+b;
return f;
}
}
Int main()
{
Moverload m1,m2,m3;
int s1,s2;
float s3;
s1=m1.add(20,30);
s2=m2.add(10,20,30);
s3=m3.add(1.5,2.5);
cout<<s1<<s2<<s3;
return 0;
}
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base Class or
Super class.
You can clearly see that above process results in duplication of same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it and
inherit the rest of the classes from the vehicle class, then we can simply avoid the
duplication of data and increase re-usability. Look at the below diagram in which the three
classes are inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three times as we
have inherited rest of the three classes from base class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the
base class we have to follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you
want to inherit this sub class for example: public, private etc. and base_class_name is the
name of the base class from which you want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class declares.
// C++ program to demonstrate implementation
// of Inheritance
#include <bits/stdc++.h>
using namespace std;
//Base class
class Parent
{
public:
int id_p;
};
public:
int id_c;
};
Prof. Supriya C, Dept. of ISE,AIT 2
Lecture Notes Module 3 Inheritance in C++
//main function
int main()
{
Child obj1;
return 0;
}
Output:
Child id is 7
Parent id is 91
In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the
public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance
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. 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.
3. 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.
Note : The private members in the base class cannot be directly accessed in the derived
class, while protected members can be directly accessed. For example, Classes B, C and D
all contain the variables x, y and z in below example. It is just question of access.
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one sub class is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
// C++ program to explain
// Single inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a vehicle
Syntax:
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public
car()
{
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is
inherited from a single base class. i.e. more than one derived class is created from a single
base class.
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};// first sub class
Prof. Supriya C, Dept. of ISE,AIT 8
Lecture Notes Module 3 Inheritance in C++
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}
Output:
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining
more than one type of inheritance. For example: Combining Hierarchical inheritance and
Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle
A special case of hybrid inheritance : Multipath inheritance:
A derived class with two base classes and these two base classes have one common base
class is called multipath inheritance. An ambiguity can arrise in this type of inheritance.
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
}
Output:
A from ClassB : 10
A from ClassC : 100
B : 20
C : 30
D : 40
In the above example, both ClassB & ClassC inherit ClassA, they both have single copy of
ClassA. However ClassD inherit both ClassB & ClassC, therefore ClassD have two copies
of ClassA, one from ClassB and another from ClassC.
If we need to access the data member a of ClassA through the object of ClassD, we must
specify the path from which a will be accessed, whether it is from ClassB or ClassC, bco’z
compiler can’t differentiate between two copies of ClassA in ClassD.
class ClassA
{
public:
int a;
};
{
public:
int c;
};
void main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
}
Output:
A : 100
B : 20
C : 30
D : 40
According to the above example, ClassD has only one copy of ClassA, therefore, statement
4 will overwrite the value of a, given at statement 3.
As we can see from the figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function member
of class A is accessed by an object of class D, ambiguity arises as to which data/function
member would be called? One inherited through B or the other inherited through C. This
confuses compiler and it displays error.
Example: To show the need of Virtual Base Class in C++
#include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello form A \n";
}
};
class B : public A {
};
class C : public A {
};
int main()
{
D object;
object.show();
}
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()
How to resolve this issue?
To resolve this ambiguity when class A is inherited in both class B and class C, it is
declared as virtual base class by placing a keyword virtual as :
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Note: virtual can be written before or after the public. Now only one copy of data/function
member will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that
use multiple inheritances. When a base class is specified as a virtual base, it can act as an
indirect base more than once without duplication of its data members. A single copy of its
data members is shared by all the base classes that use virtual base.
Example 1
#include <iostream>
using namespace std;
class A {
public:
int a;
A() // constructor
{
a = 10;
}
};
int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;
return 0;
}
Output:
a = 10
Explanation : The class A has just one data member a which is public. This class is
virtually inherited in class B and class C. Now class B and class C becomes virtual base
class and no duplication of data member a is done.
Example 2:
#include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello from A \n";
}
};
int main()
{
D object;
object.show();
}
Output:
Hello from A
Streams in C++
We give input to the executing program and the execution program gives back the output. The
sequence of bytes given as input to the executing program and the sequence of bytes that comes as
output from the executing program are called stream.
In other words, streams are nothing but the flow of data in a sequence.
The input and output operation between the executing program and the devices like keyboard and
monitor are known as “console I/O operation”. The input and output operation between the executing
program and files are known as “disk I/O operation”.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
streambuf: This class contains a pointer which points to the buffer which is used to manage
the input and output streams.
fstreambase: This class provides operations common to the file streams. Serves as a base for
fstream, ifstream and ofstream class. This class contains open() and close() function.
filebuf: Its purpose is to set the file buffers to read and write. We can also use file buffer
member function to determine the length of the file.
There are no pre-defined file stream variables, so a programmer who needs to use file streams
must declare file stream variables:
ifstream inFile; // input file stream object
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("ait.txt");
Reading a file: To create a file, use either the ofstream or fstream class, and specify the name of the
file.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream infile;
infile.open ("test.txt");
if (infile.is_open())
{
while (infile.good())
cout << (char) infile.get();
infile.close();
}
else
{
cout << "Error opening file";
}
Infile.close();
return 0;
}
Text Files
We start with a program where a file accepts a few lines as input and then displays those lines
one by one.
1. Defining a files
2. Opening a files
3. Reading from and writing to files
4. Closing files.
Using text files
A simple program to read a few lines and then display each word.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout1.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
Prof. Supriya C, Dept. of ISE,AIT 4
Lecture Notes Module 4 File Handling in C++
os.close();
ifstream is;
string line;
is.open("testout1.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include <iomanip>
int main()
{
char ch;
ofstream EntryFile("testout1.txt");
while(true)
{
cin.get(ch);
if(ch == '$') break;
Prof. Supriya C, Dept. of ISE,AIT 5
Lecture Notes Module 4 File Handling in C++
The cin is an object which is used to take input from the user but does not allow to
take the input in multiple lines. To accept the multiple lines, we use the getline()
function. It is a pre-defined function defined in a <string.h> header file used to accept
a line or a string from the input stream until the delimiting character is encountered.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // variable declaration
cout << "Enter your name :" << endl;
cin>>name;
cout<<"\nHello "<<name;
return 0;
Prof. Supriya C, Dept. of ISE,AIT 6
Lecture Notes Module 4 File Handling in C++
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // variable declaration.
cout << "Enter your name :" << endl;
getline(cin,name); // implementing a getline() function
cout<<"\nHello "<<name;
return 0;
}
Example 3:
When we do not want to read the character after space
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string profile; // variable declaration
std::cout << "Enter your profile :" << std::endl;
getline(cin,profile,' '); // implementing getline() function with a delimiting
character.
cout<<"\nProfile is :"<<profile;
}
We can also define the getline() function for character array, but its syntax is different
from the previous one.
Synatx: istream& getline(char* , int size);
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char fruits[50]; // array declaration
cout<< "Enter your favorite fruit: ";
cin.getline(fruits,30); // implementing getline() function
cout << "\nYour favorite fruit is :"<<fruits << endl;
return 0;
}
Practice Programs
Mode Description
ios::app opens a text file for appending. (appending means to add
text at the end).
ios::ate opens a file for output and move the read/write control to
the end of the file.
ios::in opens a text file for reading.
ios::out opens a text file for writing.
ios::trunc truncates the content before opening a file, if file exists. (Empties
the file)
Binary Files
A binary file is a file stored in binary format. It is a computer-readable but not
human readable. In contrast text files are stored in ASCII format. The data
inside a binary file is stored as raw bytes, which is not human readable.
Example: 13 is an integer value.
We know for every symbol, digit, or character there is some ASCII code
available. The ASCII code of 1 is 49 and for 3 the ASCII code is 51. These are
the ASCII codes for digits 1 and 3. Then what is the binary form of 49 and 51?
ASCII codes take 8 bits of binary so,
0011 0001 0011 0011 (This will be stored in the text file that is)
(ASCII code of 1) + (ASCII code of 3) = 49 + 51
= (binary code of 49) + (binary code of 51) = 0011 0001 0011 0011
This is how the bits are stored in the text file.
Questions!!!
Which file is faster? Binary file or text file?
Which file takes more space?
Benefits of text files over binary files
Example Programs
Writing to a binary file
#include <iostream>
#include <fstream>
using namespace std;
class student
{
public:
int RollNo;
char Name[30];
char Address[40];
};
int rstudent(student & TempStud)
{
cout << "\n Enter roll no.: ";
cin >> TempStud.RollNo;
cout << "\n Enter name: ";
cin >> TempStud.Name;
cout << "\n Enter address: ";
cin >> TempStud.Address;
cout << "\n";
return 0;
}
int main()
{
student s;
ofstream fout;
Prof. Supriya C, Dept. of ISE,AIT 10
Lecture Notes Module 4 File Handling in C++
Example 2:
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
public:
int roll_no;
string name;
};
int main() {
Student write_stu[2];
write_stu[0].roll_no = 1;
write_stu[0].name = "Akash";
write_stu[1].roll_no = 2;
write_stu[1].name = "Arjun";
ofstream wf("student.dat", ios::out | ios::binary); //write operations
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
for(int i = 0; i < 2; i++)
wf.write((char *) &write_stu[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" << endl;
return 1;
}
Student read_stu[2];
EXCEPTION HANDLING
Exceptions are runtime anomalies or abnormal conditions that a program
encounters during its execution.
There are two types of exceptions
a)Synchronous,
b)Asynchronous (i.e., exceptions which are beyond the program’s control, such
as disc failure, keyboard interrupts etc.)
C++ provides the following specialized keywords for this purpose:
try: the try block identifies the code block for which certain exceptions will be
activated. It should be followed by one/more catch blocks.
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.
throw: Used to throw an exception. Also used to list the exceptions that a
function throws but doesn’t handle itself.
// catch block
}
C++ example without try/catch
#include <iostream>
using namespace std;
float division(int x, int y) {
return (x/y);
}
int main () {
int i = 50;
int j = 0;
float k = 0;
k = division(i, j);
cout << k << endl;
return 0;
}
try {
k = division(i, j);
cout << k << endl;
}catch (e) {
cerr << e << endl;
}
return 0;
}
Example :
#include <iostream>
#include<exception>
using namespace std;
int main() {
try {
try
{
int x, y;
cout << "Enter the two numbers : \n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
Practice Programs:
1. Write a program to illustrate array index out of bounds exception
#include <iostream>
using namespace std;
int main() {
int a[5]={1,2,3,4,5},i;
try{
i=0;
while(1){
if(i!=5)
{
cout<<a[i]<<endl;
i++;
}
else
throw i;
}
}
catch(int i)
{
cout<<"Array Index out of Bounds Exception: "<<i<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
void sqr()
{
int s;
cout<<"\n Enter a number:";
cin>>s;
if (s>0)
{
cout<<"Square="<<s*s;
}
else
{
throw (s);
}
}
int main()
{
try
{
sqr();
}
catch (int j)
{
cout<<"\n Caught the exception \n";
}
return 0;