Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

Lecture Notes Module 1 OOPS concepts

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.

1.2: Differences b/w C & C++

No. C C++

1) C follows the procedural style C++ is multi-paradigm. It supports


programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use access modifiers for
class members to make it inaccessible
for outside users.

3) C follows the C++ follows the bottom-up approach.


top-down approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions in In C++, you can use functions in


structure. structure.

6) C does not support reference C++ supports reference variables.


variables.

Prof. Supriya C, Dept. of ISE,AIT 1


Lecture Notes Module 1 OOPS concepts

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.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided


into procedures and modules into functions and classes.

10) Exception handling is not easy in C++ provides exception handling using
C. It has to perform using other Try and Catch block.
functions.

11) C does not support the C++ supports inheritance.


inheritance.

1.3: C++ history


It was developed in 1980 by “Bjarne Stroustrup” at AT & T bell laboratories in U.S.A.

1.4: Object-Oriented Programming


 Object-oriented programming is an approach for designing the modular, reusable
software systems. The real key to the object-oriented approach is that it is a modelling
approach first.
 It uses the concepts of “objects” that have data fields and methods.
 Programmers write instructions in various programming languages to perform their
task.
 Programming is a process to provide computer- based solutions to real world
problems.

1.5: Understanding the problem


 Entities
 Attributes
 Output/Result

1.6: Object-Oriented Programming


One of the important outcomes of the study of software engineering is a new design
for programming. This programming methodology is known as object-based or object-
oriented programming.

Prof. Supriya C, Dept. of ISE,AIT 2


Lecture Notes Module 1 OOPS concepts

object-based and object-oriented programming are techniques to envision the problem as a


collection of objects that represents real-world entities. Object based language doesn’t
support inheritance and polymorphism e.g.: JavaScript, VB. OOP uses classes & objects with
inheritance e.g.: C, C++, Java.
The main goals of object-oriented programming are:

 Understanding.
 Maintenance.
 Evolution.

1.7: PROCEDURE ORIENTED PROGRAMMING SYSTEMS(POP):


1. In this approach, the problem is viewed as a sequence of the things, to be done
such as reading, calculating and printing.
2. Conventional programming, using high level languages such as COBOL,
FORTRAN and C is commonly known as procedure-oriented Programming
[POP].
3. The Primary focus on functions.

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

Function-1 Function-2 Function-3


Local data Local data Local data

 Global variables are more vulnerable to an inadvertent change by a function.


Ex: Function-1, Function-2 and Function-3 manipulate global data 1
and global data 2.
 Another serious draw back with procedural approach is that it does not model real
world problems very well, because functions are action-oriented.

Prof. Supriya C, Dept. of ISE,AIT 3


Lecture Notes Module 1 OOPS concepts

 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 ORIENTED PROGRAMMING SYSTEMS [OOPS]:

1. OOPS was invented to overcome the flaws of POP.


2. OOP treats data as critical element in the program development and does
not allow it to flow freely around the system.
3. OOP ties data and functions that operate on it and properties it from
accidental modification from outside functions.
4. OOP divides the program into a number of entities called objects.
5. An object is a unit using which both data and functions that operate on
that data are combined together can be accessed.
6. C++, JAVA is the object-oriented programming languages.
7. Organization of data & function is shown below:

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.

Prof. Supriya C, Dept. of ISE,AIT 4


Lecture Notes Module 1 OOPS concepts

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.

5. Data is hidden & cannot be accessed by external functions.


6. Objects may communicate with each other through functions.
7. New data & functions can be easily added whenever necessary.
8. Follows bottom-up approach in program design.

FEATURES and BASIC CONCEPTS OF OOPS:


 Objects
 Classes
 Data abstraction & Encapsulation
 Inheritance
 Polymorphism

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

 Variables containing data are called data members.


 Functions that can access & process the data stored in above data members are
called as member functions.

CLASSES:
 Class is a collection of objects having common features.

Prof. Supriya C, Dept. of ISE,AIT 5


Lecture Notes Module 1 OOPS concepts

 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;

DATA ABSTRACTION & ENCAPSULATION:


1. The wrapping up of data & functions into a single unit (called class) is known as
encapsulation.
2. The data is not accessible to the outside world and only those functions which are
wrapped in the class can access it.
3. These functions act as interface between data & program.
4. This insulation of data from direct access from the program is called as data hiding
or information hiding.
5. Abstraction refers to the act of representing essential features without including
the background details.
6. Classes use the concept of abstraction.
7. The attributes are sometimes called data members.
8. The functions that operate on these data are sometimes called methods or member
functions.
9. Since the classes use the concept of data abstraction, they are known as abstract
data types [ADT].

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

Prof. Supriya C, Dept. of ISE,AIT 6


Lecture Notes Module 1 OOPS concepts

POLYMORPHISM: - “having many forms”


1. Polymorphism is a phenomenon where an entity can exist in two or more forms.
2. Ex: Consider the operation of addition.
For two numbers, the operation will generate the sum.
If the operands are strings, then the operation will produce a third
string by concatenation.
3. The process of making an operator to exhibit different behaviors in
different instances is known as operator overloading.

Shape
(draw)

Circle (object) Box (object) Triangle (object)


Draw (circle) Draw (box) Draw (triangle)

4. If we use a single function name to perform different types of tasks known as


function overloading.
5. Polymorphism plays an important role in allowing objects having different internal
structure to share the same external interface.
6. Polymorphism is extensively used in inheritance.

 CONSOLE INPUT\OUTPUT IN C++:


CONSOLE OUTPUT: “cout”
1. cout is actually an object of the class ‘ostream_withassign’
2. It stands as an alias for the console output device, i.e., monitor.
3. The syntax to use cout is shown below:
4. The operator << [left shift operator] is called as the insertion operator or to put to
operator.
5. It inserts the contents of the variable on its right to the object on its left.
6. The file ‘iostream.h’ needs to be included in the source code to ensure successful
compilation because the object ‘cout’ and the ‘<<’ have been declared in that file.
7. We also can insert new line using endl object cout<<endl;
8. It acts similar to printf function of C.

Prof. Supriya C, Dept. of ISE,AIT 7


Lecture Notes Module 1 OOPS concepts

Example for cout:


Let us consider an example:
// beginning of cout.cpp----------- Comment Line
#include<iostream>// Preprocessor directive
using namespace std; // we can use names for objects and variables from standard library.
int main() //Function Header line
{
int x=10;
cout<<x; //outputing to the console
return 0;
}
Output:
10
Example 2:
Using another object called ‘’endl’
It allows us to insert a new line into the output stream. The following example
illustrates this.
#include<iostream.h>
#include<conio.h>
void main()
{
int x=10,y=20;
clrscr();
cout<<x; //outputing to the console
cout<<endl; //inserting a new line by endl
cout<<y;
getch();
}
Output:
10
20

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;

Prof. Supriya C, Dept. of ISE,AIT 8


Lecture Notes Module 1 OOPS concepts

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;
}

Prof. Supriya C, Dept. of ISE,AIT 9


Lecture Notes Module 1 OOPS concepts

CONSOLE INPUT: “cin”


o cin is actually an object of the class ‘istream_withassign’.
o It stands as an alias for the console input device, i.e. keyboard
o The syntax used is shown below:
o The operator >> is known as extraction or get from operator.
o It assigns or extracts the value from the keyboard and assigns it to variable on its right.
o The file ‘iostream.h’ needs to be included in the source code to ensure successful
compilation because the object ‘cin’ and the >> have been declared in that file.
o Just like the insertion operator the extraction operator works equally well with
variables of all fundamental types as its right hand operand.
o It does not need the format specifiers that are needed in the scanf if C.
Example for cin:

# 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:

Prof. Supriya C, Dept. of ISE,AIT 10


Lecture Notes Module 1 OOPS concepts

Enter a two number: 45 34


The entered numbers is: 45 and 34

Classes and Objects


Structures in C
In C programming, a struct (or structure) is a collection of variables (can be of different
types) under a single name.
struct structureName {
dataType member1;
dataType member2;

...
};

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>

// create struct with person1 variable


struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {

// assign value to name of person1


strcpy(person1.name, "George Orwell");

// assign values to other person1 variables

Prof. Supriya C, Dept. of ISE,AIT 11


Lecture Notes Module 1 OOPS concepts

person1.citNo = 1984;
person1. salary = 2500;

// print struct variables


printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);

return 0;
}

Class – blueprint of an object


Classes and objects are the two main aspects of object-oriented programming.
Class -Fruit Object – Apple, Orange
Class – Car Object – Volvo, Audi

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”;
}
}

Object – It is an instance of that class


When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
Syntax:
ClassName ObjectName;

Prof. Supriya C, Dept. of ISE,AIT 12


Lecture Notes Module 1 OOPS concepts

Accessing data members and member functions:

“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() .

Member Functions in classes: There are 2 ways to define a member function

 Inside class definition


 Outside class definition
Example : Class with single object declaration
class MyClass
{
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

Example: Multiple object declaration


class Car {
public:
string brand;
string model;
int year;
};

int main() {

Prof. Supriya C, Dept. of ISE,AIT 13


Lecture Notes Module 1 OOPS concepts

// Create an object of Car


Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}

Methods and Messages


C++ class methods are user-defined functions that can be used within an instance of the class.
A dot notation. is used before method names to distinguish them from regular functions.
There are two ways to define functions that belongs to a class:
1. Inside class definition
2. Outside class definition

Inside the class


class MyClass
{
public: // Access specifier
void myMethod()
{ // Method/function defined inside the class
cout << "Hello World!";
}
};

int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}

Prof. Supriya C, Dept. of ISE,AIT 14


Lecture Notes Module 1 OOPS concepts

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;

Prof. Supriya C, Dept. of ISE,AIT 15


Lecture Notes Module 1 OOPS concepts

Advantages of Data Abstraction

 Helps the user to avoid writing the low-level code


 Avoids code duplication and increases reusability.
 Can change the internal implementation of the class independently without affecting
the user.
 Helps to increase the security of an application or program as only important details
are provided to the user.
 It reduces the complexity as well as the redundancy of the code, therefore increasing
the readability.

Data Abstraction can be achieved in two ways:

o Interface
o Abstract class

C++ programming there is no built-in concept of interfaces.


I. In order to create an interface, we need to create an abstract class which is having
only pure virtual methods.
II. In C++, Interfaces are also called pure abstract classes.

Pure Virtual Functions

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.

Synatx: virtual datatype functionName(parameter1, parameter2,…) = 0;

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.

Rules While Using Interfaces


o Declare only pure virtual functions. (No definition)
o For pure virtual functions assign only 0.
o Cannot create an instance of the class.

Prof. Supriya C, Dept. of ISE,AIT 16


Lecture Notes Module 1 OOPS concepts

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

Abstraction using Abstraction in


classes header files

Prof. Supriya C, Dept. of ISE,AIT 17


Lecture Notes Module 1 OOPS concepts

Abstraction using classes


An abstraction can be achieved using classes. A class is used to group all the data members
and member functions into a single unit by using the access specifiers. A class has the
responsibility to determine which data member is to be visible outside and which is not.
Abstraction using header files
An another type of abstraction is header file. For example, pow() function available is used to
calculate the power of a number without actually knowing which algorithm function uses to
calculate the power. Thus, we can say that header files hides all the implementation details
from the user.

Access Specifiers Implement 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.

Example 1: Using header files


#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
std::cout << "Cube of n is : " <<result<< std::endl;
return 0;
}

Example 2: Using classes


#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:

Prof. Supriya C, Dept. of ISE,AIT 18


Lecture Notes Module 1 OOPS concepts

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.

Prof. Supriya C, Dept. of ISE,AIT 19


Lecture Notes Module 1 OOPS concepts

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.

Prof. Supriya C, Dept. of ISE,AIT 20


Lecture Notes Module 2 Functions in C++

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.

The following tokens are available in C++:

 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.

Some rules must be followed when choosing an identifier:

o The first character must be a letter or an underscore.


o Identifiers cannot be the same as a keyword.
o Identifiers cannot contain any spaces or special characters except for the
underscore.
o Identifiers are case-sensitive, meaning that a variable named "myVariable" is
different from a variable named "myvariable".

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.

Prof. Supriya C, Dept. of ISE,AIT 1


Lecture Notes Module 2 Functions in C++

Strings: Strings are objects that signify sequences of characters which is enclosed inside the
double quotes.

Char string-name[size];

Char city[9]=”New York”;

Scope Resolution Operator

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;
}

Prof. Supriya C, Dept. of ISE,AIT 2


Lecture Notes Module 2 Functions in C++

To access the hidden variable /function of a program

#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.

Prof. Supriya C, Dept. of ISE,AIT 3


Lecture Notes Module 2 Functions in C++

• 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.

• Special assignment expressions: An expression can be categorized further depending


upon the way the values are assigned to the variables.

 Chained assignment: Chained assignment is an assignment expression in which


the same value is assigned to more than one variable, using a single statement.
For example, consider these statements.

a = (b=20); or a=b=20;
int a=b=30; // illegal
int a=30, int b=30; //valid

 Embedded assignment: Embedded assignment is an assignment expression,


which is enclosed within another assignment expression. For example, consider
this statement

a=20+(b=30); //equivalent to b=30; a=20+30;

 Compound Assignment: Compound Assignment is an assignment expression,


which uses a compound assignment operator that is a combination of the
assignment operator with a binary arithmetic operator. For example, consider
this statement.

a + =20; //equivalent to a=a+20;

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.

Prof. Supriya C, Dept. of ISE,AIT 4


Lecture Notes Module 2 Functions in C++

Syntax: return_type name of the function (argument list);

Void add(int x,int y);

Example:

Int add(int x,int y); //function declaration

Int main()

Int a=10,b=20,c;

c = add(a,b);

cout<<”Add”<<c;

Int add(int x,int y)

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

Int& add(int a,int b);

This function returns a reference of the variable

#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&

We cannot return a constant from a function

Int& test()

{ return 2; }

We cannot return a local variable from this function

Int &test()

{ int n=2;return n;}

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.

Prof. Supriya C, Dept. of ISE,AIT 6


Lecture Notes Module 2 Functions in C++

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:

inline void printSum(int num1,int num2) {


cout << num1 + num2 << "\n";
}
int main() {
// call the inline function
// first call
printSum(10, 20);
// second call
printSum(2, 5);
// third call
printSum(100, 400);
return 0;
}

Prof. Supriya C, Dept. of ISE,AIT 7


Lecture Notes Module 2 Functions in C++

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.

Prof. Supriya C, Dept. of ISE,AIT 8


Lecture Notes Module 2 Functions in C++

Examples

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

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;
}

Prof. Supriya C, Dept. of ISE,AIT 9


Lecture Notes Module 3 Inheritance in C++

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.

The article is divided into following subtopics:


1. Why and when to use inheritance?
2. Modes of Inheritance
3. Types of Inheritance

Why and when to use inheritance?


Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If
we create these classes avoiding inheritance then we have to write all of these functions in
each of the three classes as shown in below figure:

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:

Prof. Supriya C, Dept. of ISE,AIT 1


Lecture Notes Module 3 Inheritance in C++

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;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent
{

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;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;

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.

// C++ Implementation to show that a derived class


// doesn’t inherit access to private data members.
// However, it does inherit a full parent object
class A
{
public:
int x;
protected:
int y;
private:
int z;
};

Prof. Supriya C, Dept. of ISE,AIT 3


Lecture Notes Module 3 Inheritance in C++

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
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};
The below table summarizes the above three modes and shows the access specifier of the
members of base class in the sub class when derived in public, protected and private modes:

Types of Inheritance in 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.

Prof. Supriya C, Dept. of ISE,AIT 4


Lecture Notes Module 3 Inheritance in C++

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;
}
};

// sub class derived from two base classes


class Car: public Vehicle{

};

// 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

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can


inherit from more than one classes. i.e one sub class is inherited from more than one base
class

Prof. Supriya C, Dept. of ISE,AIT 5


Lecture Notes Module 3 Inheritance in C++

Syntax:

class subclass_name : access_mode base_class1, access_mode base_class2, ....


{
//body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for
every base class must be specified.

// C++ program to explain


// multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
void display()
{
cout << "This is a Vehicle" << endl;
}
};

// second base class


class FourWheeler {
public:
fourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle, public FourWheeler {

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

Prof. Supriya C, Dept. of ISE,AIT 6


Lecture Notes Module 3 Inheritance in C++

Output:
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from

another derived class.


// C++ program to implement
// Multilevel Inheritance
#include <iostream>
using namespace std;

// 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()
{

Prof. Supriya C, Dept. of ISE,AIT 7


Lecture Notes Module 3 Inheritance in C++

cout<<"Car has 4 Wheels"<<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
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.

// C++ program to implement


// Hierarchical Inheritance
#include <iostream>
using namespace std;

// 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++

class Car: public Vehicle


{

};

// second sub class


class Bus: public Vehicle
{

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}
Output:

Prof. Supriya C, Dept. of ISE,AIT 9


Lecture Notes Module 3 Inheritance in C++

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:

// C++ program for Hybrid 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";
}
};

// first sub class


class Car: public Vehicle

Prof. Supriya C, Dept. of ISE,AIT 10


Lecture Notes Module 3 Inheritance in C++

};

// second sub class


class Bus: public Vehicle, public Fare
{

};

// 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.

Prof. Supriya C, Dept. of ISE,AIT 11


Lecture Notes Module 3 Inheritance in C++

Consider the following program:


// C++ program demonstrating ambiguity in Multipath Inheritance

#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};

class ClassB : public ClassA


{
public:
int b;
};
class ClassC : public ClassA
{
public:
int c;
};

class ClassD : public ClassB, public ClassC


{
public:
int d;
};
void main()
{

ClassD obj;

//obj.a = 10; //Statement 1, Error


//obj.a = 100; //Statement 2, Error
obj.ClassB::a = 10; //Statement 3
obj.ClassC::a = 100; //Statement 4

obj.b = 20;
obj.c = 30;
obj.d = 40;

cout<< "\n A from ClassB : "<< obj.ClassB::a;


cout<< "\n A from ClassC : "<< obj.ClassC::a;

cout<< "\n B : "<< obj.b;


cout<< "\n C : "<< obj.c;

Prof. Supriya C, Dept. of ISE,AIT 12


Lecture Notes Module 3 Inheritance in C++

cout<< "\n D : "<< obj.d;

}
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.

There are 2 ways to avoid this ambiguity:


1. Use scope resolution operator
2. Use virtual base class

Avoiding ambiguity using scope resolution operator:


Using scope resolution operator we can manually specify the path from which data member
a will be accessed, as shown in statement 3 and 4, in the above example.
filter_none
edit
play_arrow
brightness_4
obj.ClassB::a = 10; //Statement 3
obj.ClassC::a = 100; //Statement 4
Note : Still, there are two copies of ClassA in ClassD.
Avoiding ambiguity using virtual base class:
include<iostream.h>
#include<conio.h>

class ClassA
{
public:
int a;
};

class ClassB : virtual public ClassA


{
public:
int b;
};
class ClassC : virtual public ClassA
Prof. Supriya C, Dept. of ISE,AIT 13
Lecture Notes Module 3 Inheritance in C++

{
public:
int c;
};

class ClassD : public ClassB, public ClassC


{
public:
int d;
};

void main()
{

ClassD obj;

obj.a = 10; //Statement 3


obj.a = 100; //Statement 4

obj.b = 20;
obj.c = 30;
obj.d = 40;

cout<< "\n A : "<< obj.a;


cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;

}
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.

Virtual base class in C++


Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
Need for Virtual Base Classes:
Consider the situation where we have one class A .This class is A is inherited by two other
classes B and C. Both these class are inherited into another in a new class D as shown in
figure below.

Prof. Supriya C, Dept. of ISE,AIT 14


Lecture Notes Module 3 Inheritance in C++

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";

Prof. Supriya C, Dept. of ISE,AIT 15


Lecture Notes Module 3 Inheritance in C++

}
};

class B : public A {
};

class C : public A {
};

class D : public B, public C {


};

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 for Virtual Base Classes:

Syntax 1:
class B : virtual public A

{
};

Syntax 2:
class C : public virtual A
{
};

Prof. Supriya C, Dept. of ISE,AIT 16


Lecture Notes Module 3 Inheritance in C++

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;
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

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;

Prof. Supriya C, Dept. of ISE,AIT 17


Lecture Notes Module 3 Inheritance in C++

class A {
public:
void show()
{
cout << "Hello from A \n";
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}
Output:
Hello from A

Prof. Supriya C, Dept. of ISE,AIT 18


Lecture Notes Module 4 File Handling in C++

Module 4 -File handling in C++


File handling is used to store data permanently in a computer. Using file handling we can
store our data in secondary memory (Hard disk).
How to achieve the File Handling
For achieving file handling we need to follow the following steps:-
1. STEP 1-Naming a file
2. STEP 2-Opening a file
3. STEP 3-Writing data into the file
4. STEP 4-Reading data from the file
5. STEP 5-Closing a file.

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”.

Classes for File stream operations


The I/O system of C++ contains a set of classes which define the file handling methods.
These include ifstream, ofstream and fstream classes. These classes are derived from
fstream and from the corresponding iostream class. These classes, designed to manage the
disk files, are declared in fstream and therefore we must include this file in any program that
uses files.

Prof. Supriya C, Dept. of ISE,AIT 1


Lecture Notes Module 4 File Handling in C++

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

Prof. Supriya C, Dept. of ISE,AIT 2


Lecture Notes Module 4 File Handling in C++

ofstream outFile; // output file stream object

Example file programs


Formatted and Unformatted I/O
Create and Write To a File : To create a file, use either the ofstream or fstream class, and specify
the name of the file.To write to the file, use the insertion operator (<<).

#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("ait.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}

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");

Prof. Supriya C, Dept. of ISE,AIT 3


Lecture Notes Module 4 File Handling in C++

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;
}

Using get() and put( )


Below example programs reads lines until $ and displays the lines as they are back on
the screen. It uses two functions for reading and writing characters, that is, get() and
put().
Their syntax is as follows:
 cin.get(ch) (reads a character from cin and stores what is read in ch)
 cout.put(ch) (reads a character ch and writes to cout)

#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++

EntryFile << ch;


}
EntryFile.close();
ifstream DisplayFile("testout1.txt");
while(!DisplayFile.eof())
{
// Do not skip white space
DisplayFile.unsetf(ios::skipws);
DisplayFile >> ch;
cout << ch;
}
DisplayFile.close();
return 0;
}
Using getline()

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.

Exampe 1: without using getline()

#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++

Example 2 : Using getline()

#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;
}

Example 4: Getline Character Array

Prof. Supriya C, Dept. of ISE,AIT 7


Lecture Notes Module 4 File Handling in C++

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)

Prof. Supriya C, Dept. of ISE,AIT 8


Lecture Notes Module 4 File Handling in C++

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

Binary File functions


read( )- read a block of binary data or reads a fixed number of bytes from the
specified stream and store in a buffer.
Syntax : Stream_object.read((char *)& Object, sizeof(Object));
E.g file.read((char *)&s, sizeof(s));
write( ) – write a block of binary data or writes fixed number of bytes from a
specific memory location to the specified stream.
Syntax : Stream_object.write((char *)& Object, siz
eof(Object));
E.g wf.write((char *)&s, sizeof(s));
Prof. Supriya C, Dept. of ISE,AIT 9
Lecture Notes Module 4 File Handling in C++

wf.good(): Used to determine if the process was successful or if there was


any error and if so, the error occurrence is informed to the user.
Both functions take two arguments.
1. The first is the address of variable, and the second is the length of that variable in
bytes. The address of variable must be type cast to type char*(pointer to character
type)
2. The data written to a file using write( ) can only be read accurately using read( ).

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++

fout.open("MCA.dat", ios::out | ios::binary | ios::trunc);


if(!fout.is_open())
cout << "File cannot be opened \n";
char Continue = 'y';
do
{
rstudent(s);
fout.write((char*) &fout, sizeof(s));
if(fout.fail())
cout << "File write failed";
cout << "Do you want to continue? (y/n): ";
cin >> Continue;
} while(Continue != 'n');
fout.close();
return 0;
}

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";

Prof. Supriya C, Dept. of ISE,AIT 11


Lecture Notes Module 4 File Handling in C++

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];

ifstream rf("student.dat", ios::in | ios::binary);


if(!rf) {
cout << "Cannot open file!" << endl;
return 1;
}
for(int i = 0; i < 2; i++)
rf.read((char *) &read_stu[i], sizeof(Student));
rf.close();
if(!rf.good()) {
cout << "Error occurred at reading time!" << endl;
return 1;
}
cout<<"Student Details:"<<endl;
for(int i=0; i < 2; i++) {
cout << "Roll No: " << read_stu[i].roll_no << endl;
cout << "Name: " << read_stu[i].name << endl;
cout << endl;
}
return 0;
}
Prof. Supriya C, Dept. of ISE,AIT 12
Lecture Notes Module 5 Exception Handling

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.

Prof. Supriya C, Dept. of ISE,AIT 1


Lecture Notes Module 5 Exception Handling

Why Exception Handling?


1. You will separate your error handling code from your normal code. The
code will be more readable and easier to maintain.
2. Functions can handle the exceptions they choose. Even if a function throws
many exceptions, it will only handle some. The caller will handle the
uncaught exceptions.
Syntax:
try {
// the protected code
} catch( Exception_Name exception1 ) {
// catch block
} catch( Exception_Name exception2 ) {
// catch block
} catch( Exception_Name exceptionN ) {
Prof. Supriya C, Dept. of ISE,AIT 2
Lecture Notes Module 5 Exception Handling

// 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;
}

C++ example using try/catch : Throwing Exceptions


Example 1:
#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;

Prof. Supriya C, Dept. of ISE,AIT 3


Lecture Notes Module 5 Exception Handling

try {
k = division(i, j);
cout << k << endl;
}catch (e) {
cerr << e << endl;
}
return 0;
}

Multiple Catch statements


It is also possible that a program segment has more than one condition to throw an exception.
In such cases, we can associate more than one catch statement with a try (similar to switch
statement). The format of multiple catch statements is as follows:
try
{
// try block
}
catch (type1 arg)
{
// catch section1
}
catch (type2 arg)
{
// catch section2
}
.......
.......
catch (typen arg)
{
// catch section-n
}

Example :

#include <iostream>
#include<exception>
using namespace std;
int main() {
try {

Prof. Supriya C, Dept. of ISE,AIT 4


Lecture Notes Module 5 Exception Handling

std::cout<<"Please enter the age"<<std::endl;


int age=0;
std::cin>>age;
if (age<0 || age>100)
{
throw 'a';
}
}
catch (int e)
{
std::cout << "Access denied - You must enter a valid age."<<e<<std::endl;
}
catch (char e)
{
std::cout << "Access denied - You must not enter a char value."<<e<<std::endl;
}
catch (...)
{
std::cout << "Access denied - You must not enter a char value."<<std::endl;
}
}

C++ User-Defined Exceptions


The new exception can be defined by overriding and inheriting exception class
functionality.
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!\n";
}
};
int main()
{

Prof. Supriya C, Dept. of ISE,AIT 5


Lecture Notes Module 5 Exception Handling

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();
}
}

Differences between Checked and unchecked exceptions


Checked Exceptions Unchecked Exceptions
Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
The compiler checks a checked exception. The compiler does not check these types of
exceptions.
These types of exceptions can be handled at the These types of exceptions cannot be a catch or
time of compilation. handle at the time of compilation, because they
get generated by the mistakes in the program.
They are the sub-class of the exception class. They are runtime exceptions and hence are not a
part of the Exception class.

Examples of Checked exceptions: Examples of Unchecked Exceptions:

 File Not Found Exception  No Such Element Exception


 No Such Field Exception  Undeclared Throwable Exception
 Interrupted Exception  Empty Stack Exception
 No Such Method Exception  Arithmetic Exception
 Null Pointer Exception
 Class Not Found Exception
 Array Index Out of Bounds Exception
 Security Exception

Prof. Supriya C, Dept. of ISE,AIT 6


Lecture Notes Module 5 Exception Handling

Benefits of Exception handling-


(a) Exception handling can control run tune errors that occur in the program.
(b) It can avoid abnormal termination of the program and also shows the behavior
of program to users.
c)It can provide a facility to handle exceptions, throws message regarding
exception and completes the execution of program by catching the exception
(d) It can separate the error handling code and normal code by using try-catch
block.
(e) It can produce the normal execution flow for a program.
(f) It can implement a clean way to propagate error. that is. when an invoking
method cannot manage a particular situations, then it throws an exception and
asks the invoking method to deal with such situation.
(g) It develops a powerful coding which ensures that the exceptions can be
prevented.
(h) It also allows to handle related exceptions by single exception handler. All the
related errors are grouped together by using exceptions. And then they are handled
by using single exception handler.

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)
{

Prof. Supriya C, Dept. of ISE,AIT 7


Lecture Notes Module 5 Exception Handling

cout<<a[i]<<endl;
i++;
}
else
throw i;
}
}
catch(int i)
{
cout<<"Array Index out of Bounds Exception: "<<i<<endl;
}
return 0;
}

2. Write a C++ program to define function that generates exception

#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;

Prof. Supriya C, Dept. of ISE,AIT 8


Lecture Notes Module 5 Exception Handling

Prof. Supriya C, Dept. of ISE,AIT 9

You might also like