0% found this document useful (0 votes)
12 views14 pages

BCA-II oops C++ Uninnt 3,4,5

The document covers Object Oriented Programming (OOP) concepts in C++, specifically focusing on constructors, destructors, operator overloading, and inheritance. It explains various types of constructors, including default, parameterized, and copy constructors, as well as dynamic memory allocation. Additionally, it discusses operator overloading rules and types, and outlines different inheritance types in C++.

Uploaded by

vicky483788
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

BCA-II oops C++ Uninnt 3,4,5

The document covers Object Oriented Programming (OOP) concepts in C++, specifically focusing on constructors, destructors, operator overloading, and inheritance. It explains various types of constructors, including default, parameterized, and copy constructors, as well as dynamic memory allocation. Additionally, it discusses operator overloading rules and types, and outlines different inheritance types in C++.

Uploaded by

vicky483788
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Object Oriented PrOgramming with c++

Lecture nOtes Of unit 3,4 &5


bca-ii sem & b.sc(cs)

UNIT-III
Constructors and Destructors: Constructors, Parametric Constructors, Multiple Constructors in a class, constructors
with default arguments. Dynamic initialization of objects, copy constructors, dynamic constructors, destructors.
Operator Overloading & Type Conversions: Definition of Overloading, &Operator Overloading, rules for Overloading
Operators, Overloading Unary Operators, Binary Operators, Binary Operators using Friends.

Constructor
C++ is an object oriented programming (OOP) language which provides a special member function called constructor
for initializing an object when it is created. This is known as automatic initialization of objects. Constructor has the
same name as that of the class’s name and its main job is to initialize the value of the class. Constructors have no
return type, not even void.

Characteristics of Constructors
A constructor for a class is needed so that the compiler automatically initializes an object as soon as it is created. A
class constructor if defined is called whenever a program creates an object of that class. The constructor functions
have some special characteristics which are as follows:
• They should be declared in the public section.
• They are invoked directly when an object is created.
• They don’t have return type, not even void and hence can’t return any values.
• They can’t be inherited; through a derived class, can call the base class constructor.
• Constructors can’t be virtual.
• Constructor can be inside the class definition or outside the class definition.
• Constructor can’t be friend function.
• They make implicit calls to the operators new and delete when memory allocation is required.

A constructor is a special method that is created when the object is created or defined. This particular method holds
the same name as that of the object and it initializes the instance of the object whenever that object is created. The
constructor also usually holds the initializations of the different declared member variables of its object.

Constructor Overloading:-
When we use more than one constructor function defined in a class, then it is called constructor overloading or use of
multiple constructor in a class. It is used to increase the flexibility of a class by having more number of constructors for
a single class. Overloading constructors in C++ programming gives us more than one way to initialize objects in a
class.

Type of constructor
In object oriented programming (OOP’s), a constructor in a class is used to initialize the value of the object. It prepares
the new object for use by initializing its legal value. We will discuss main types of constructors, their features and
applications in the following section:
1. Default Constructor :- A constructor that has zero parameter list or in other sense, a constructor that accept no
arguments is called a zero argument constructor or default constructor. If default constructor is not defined in the
source code by the programmer, then the compiler defined the default constructor implicitly during compilation.
If the default constructor is defined explicitly in the program by the programmer, then the compiler will not define
the constructor implicitly, but it calls the constructor implicitly.
2. Parameterized Constructor:-We can write a constructor in C++ which can accept parameters for its invocation.
Such constructor that can take the arguments are called parameterized constructor. In other words; “Declaring a
constructor with arguments hides the default constructor”.
3. Copy Constructor:- A copy constructor is used to declare and initialize an object from another object. Thus the
process of initializing through a copy constructor is known as copy initialization. The copy constructors are used in
the following situations
• The initialization of an object by another object of the same class.
• Return of objects as a function value.
The syntax of copy constructor is: class_name(class_name &ptr)

Example of Constructor
#include <iostream.h>
class Emp
{
private:

OOPS with C++ Mrs. Kirti Verma Page- 1


float sal; // data member
int empno; // data member
public:
Emp() // default Constructor with no arguments
{
sal = 2000;
empno=111;
}
Emp(int e, float s ) // Constructor with an argument i.e. parameterised Constructor
{
empno=e;
Sal=s;
}
Emp( Emp &e)
{
empno=e.empno;
sal=e.sal;
}
};
void main()
{
Emp e1; // static declaration of object e1
e1.disp();
float salary;
int eno;
cout<<endl<<”Enter Employee Number and salary”;
cin>> eno>>salary;
emp e2(eno,sal) //dynamic declaration
e2.disp();
e1=e2;
cout<<”\n e1 after copy constructor ”;
e1.disp();
}

Dynamic Constructor in C++


When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as
dynamic constructor. By using this, we can dynamically initialize the objects. The constructor which allocates a block
of memory that can be accessed by the objects at run time is known as Dynamic Constructor.In simple terms, a
Dynamic constructor is used to dynamically initialize the objects, that is memory is allocated at run time.
To define a dynamic constructor in C++, the new keyword is used. New is a keyword in C++ that is used for the
dynamic allocation of memory and is used for dynamically initializing objects.
Example of Dynamic Constructor
#include <iostream.h>
class A
{
int *value;
public:
A()//Default constructor
{
value = new int; //Memory allocation at run time
*value = 1729;
}
A(int p_value) //Parameterised constructor
{
value = new int; //Memory allocation at run time
*value= p_value+1;
}
void display()
{
cout<< *value <<endl;
}
~A() //destructor
{
delete value ;
}
};
void main()
{
A obj1, obj2(7225);
cout<<"The value of object obj1 is: ";
obj1.display();// default constructor
cout<<"\nThe value of object 0bj2 is: ";
obj2.display();// parameterised constructor
}

OOPS with C++ Mrs. Kirti Verma Page- 2


Destructors
Destructors are functions that are complimentary to constructors. Member function called destructor is used to destroy
the objects when it is no longer required. A destructor, as the name implies, is used to destroy the objects that have
been created by using constructor. They de-initialize objects when they are destroyed. A destructor is invoked when
an object of the class goes out of scope, or when the memory occupied by it is de allocated using the delete operator.
A destructor is a function that has the same name as that of the class but is prefixed with a ~ (tilde).

Operator Overloading
Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in
C++ without changing its original meaning. C++ has the ability to provide the operators with a special meaning for a
data type, this ability is known as operator overloading. C++ provides a special function to change the current
functionality of some operators within its class which is often called as operator overloading.
Syntax:-
returnType operator symbol (arguments)
{
... .. ...
}
Types of Operator Overloading in C++
• Overloading Unary Operator.
• Overloading Binary Operator.

Rules for Overloading Operators


• Operators that cannot be overloaded are .* :: ?:
• In the case of a non-static member function, the binary operator should have only one argument and the
unary should not have an argument.
• In the case of a friend function, the binary operator should have only two arguments and the unary should
have only one argument.
• Operators that cannot be overloaded when declaring that function as friend function are = () [] ->.

Overloading Unary Operator


Let us consider overloading (-) unary operator. In the unary operator function, no arguments should be passed. It
works only with one class object. It is the overloading of an operator operating on a single operand. A unary operator
is an operator that operates on a single operand, such as changing the sign of a number or incrementing
/decrementing its value. The most common unary operators in C++ are the unary plus (+) and unary minus (-)
operators. The following are some examples of unary operators in C++, including:
• Unary plus (+): This operator is used to indicate a positive value.
• Unary minus (-): This operator is used to indicate a negative value.
• Increment (++): This operator is used to increase the value of the operand by one.
• Decrement (--): This operator is used to decrease the value of the operand by one.
• Logical NOT (!): This operator is used to get the opposite value of a boolean expression.

C++ program to show unary operator overloading


#include <iostream .h>
class Distance {
public:
int feet, inch; // Constructor to initialize the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to perform decrement operation of Distance object
void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " <<
feet << "'" << inch;
}
};
void main()
{
Distance d1(8, 9);
-d1;
}

OOPS with C++ Mrs. Kirti Verma Page- 3


Overloading binary operator
An operator which contains two operands to perform a operation is called the Binary Operator Overloading. It is a
polymorphic compile technique where a single operator can perform various functionalities by taking two operands
from the programmer or user.
// C++ program to add two distances using binary plus (+) operator overloading
#include <iostream,h>
class Length
{
private:
int feet, inches;
public:
void getdata(void)
{
cout << "Enter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
}
void disp(void)
{
cout << "Feet:" << feet << "\t"<< "Inches:" << inches << endl;
}
// add two length using + operator overloading
Length operator+(Length& len)
{
Length tmp; // to add two distances
tmp.inches = inches + len.inches;
tep.feet = feet + 1en.feet + (tmp.inches / 12);
tmp.inches = tmp.inches % 12;
return tmp;
}
};
void main()
{
Length L1,L2,L3;
cout << "Enter first distance:" << endl;
L1.getdata();
cout << endl<< "Enter second distance:" << endl;
L2.getdata();
L3 = L1 + L2; // add two distances
cout<< endl<< "Total Distance:";
L3.disp();
}

Binary Operators overloading using Friends


• Friend function are more useful in operator overloading
• They are more flexible then member function,
• The different between member function and friend function is that member function arguments explicitly
• The friend functions needs the parameter should be explicitly fast.
• Friend function requires two operands to be passed as arguments

Example:
#include <iostream.h>
class Complex
{
private:
int real;
int img;
public:
Complex (int r, int i )
{
real = r;
img = i;
}
void Disp()
{
cout << real << "+i" << img;
}
friend Complex operator + (Complex c1, Complex c2);
};
Complex operator + (Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;

OOPS with C++ Mrs. Kirti Verma Page- 4


}
void main ()
{
Complex C1(10, 30), C2(10, 50);
C1.Disp();
cout << " + ";
C2.Disp();
cout << " = ";
Complex C3 = C1 + C2;
C3.Disp();
}

Type conversion :
Type Conversions In a mixed expression constants and variables are of different data types. The assignment
operations causes automatic type conversion between the operand as per certain rules. The type of data to the right
of an assignment operator is automatically converted to the data type of variable on the left at the compiler time.
example –
int x=30;
float y;
y=x; // y==30.000000.

There are three types of situations that arise where data conversion are between incompatible types.
1. Conversion from built in type to class type.
2. Conversion from class type to built in type.
3. Conversion from one class type to another.

Type Casting: In typing casting, a data type is converted into another data type by the programmer using the casting
operator during the program design. In typing casting, the destination data type may be smaller than the source data
type when converting the data type to another data type, that’s why it is also called narrowing conversion and may
lead to data loss
float x=3.14;
byte y;
y=(byte)x; // we are converting float(source) data type into byte(target) data type.

Inline Functions in C++


C++ provides inline functions to reduce the function call
overhead. An inline function is a function that is expanded in
line when it is called. When the inline function is called
whole code of the inline function gets inserted or substituted
at the point of the inline function call. This substitution is
performed by the C++ compiler at compile time. An inline
function may increase efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
Inline functions Advantages:
• Function call overhead doesn’t occur.
• It also saves the overhead of push/pop variables on the stack when a function is called.
• It also saves the overhead of a return call from a function.
• When you inline a function, you may enable the compiler to perform context-specific optimization on the body of
the function. Such optimizations are not possible for normal function calls. Other optimizations can be obtained by
considering the flows of the calling context and the called context.
• An inline function may be useful (if it is small) for embedded systems because inline can yield less code than the
function called preamble and return.

OOPS with C++ Mrs. Kirti Verma Page- 5


UNIT –IV
Inheritance: defining derived classes, single inheritance, multilevel inheritance, multiple inheritance, hierarchical
inheritance, hybrid inheritance, virtual base class, abstract classes, constructors in derived classes, member class,
nesting of class.

Inheritance:
C++ strongly supports the concept of reusability. The C++ classes can be used again in several ways. Once a class
has been written and tested, it can be adopted by another programmers. This is basically created by defining the new
classes, reusing the properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class being defined "is" also
an object of inherited class. The old class is called 'BASE' class and the new one is called 'DERIEVED' class. It is a
feature that enables a class to acquire properties and characteristics of another class.

Defining Derived Classes


A derived class is specified by defining its relationship with the base class in addition to its own details.
syntax
class d_classname : Access_specifier baseclass name
{
// members of derived class
};
The colon indicates that the a-class name is derived from the base class name. The access specifier or the visibility
mode is optional and, if present, may be public, private or protected. By default it is private. Visibility mode describes
the status of derived features e.g.
class xyz //base class
{
members of xyz
};
class ABC : public xyz //public derivation
{
members of ABC
};
class ABCD: XYZ //private derivation (by default)
{
members of ABCD
};
In the inheritance, some of the base class data elements and member functions are inherited into the
derived class. We can add our own data and member functions and thus extend the functionality of
the base class

Types of Inheritance in C++


There are five types of inheritance in C++ based upon how the derived class inherits its features from the base class.
These five types are as follows:
1. Single Inheritance
Single Inheritance is the most primitive among all the types of inheritance in C++. In this inheritance, a single class
inherits the properties of a base class. All the data members of the base class are accessed by the derived class
according to the visibility mode (i.e., private, protected, and public) that is specified during the inheritance.
Syntax
class base_class_1
{
// class definition
};
class derived_class: visibility_mode base_class_1
{
// class definition
};
A single derived_class inherits a single base_class. The visibility_mode is specified while declaring the derived class
to specify the control of base class members within the derived class.

2. Multiple Inheritance
The inheritance in which a class can inherit or derive the characteristics of multiple classes, or a derived class can
have over one base class, is known as Multiple Inheritance. It specifies access specifiers separately for all the base
classes at the time of inheritance. The derived class can derive the joint features of all these classes and the data
members of all the base classes are accessed by the derived or child class according to the access specifiers.

OOPS with C++ Mrs. Kirti Verma Page- 6


Syntax
class base_class_1
{
// class definition
};
class base_class_2
{
// class definition
};
class derived_class: visibility_mode_1 base_class_1,
visibility_mode_2 base_class_2
{
// class definition
};
The derived_class inherits the characteristics of two base classes, base_class_1 and base_class_2. The
visibility_mode is specified for each base class while declaring a derived class. These modes can be different for
every base class.
3. Multilevel Inheritance
The inheritance in which a class can be derived from another derived class is known as Multilevel Inheritance.
Suppose there are three classes A, B, and C. A is the base class that derives from class B. So, B is the derived class
of A. Now, C is the class that is derived from class B. This makes class B, the base class for class C but is the derived
class of class A. This scenario is known as the Multilevel Inheritance. The data members of each respective base
class are accessed by their respective derived classes according to the specified visibility modes.
Syntax
class class_A
{
// class definition
};
class class_B: visibility_mode class_A
{
// class definition
};
class class_C: visibility_mode class_B
{
// class definition
};
The class_A is inherited by the sub-class class_B. The class_B is inherited by the
subclass class_C. A subclass inherits a single class in each succeeding level.

4. Hierarchical Inheritance
The inheritance in which a single base class inherits multiple derived classes is known as the Hierarchical Inheritance.
This inheritance has a tree-like structure since every class acts as a base class for one or more child classes. The
visibility mode for each derived class is specified separately during the inheritance and it accesses the data members
accordingly.
Syntax
class class_A
{
// class definition
};
class class_B: visibility_mode class_A
{
// class definition
};

class class_C : visibility_mode class_A


{
// class definition
};
class class_D: visibility_mode class_B
{
// class definition
};
class class_E: visibility_mode class_C
{
// class definition
};
The subclasses class_B and class_C inherit the attributes of the base class class_A. Further, these two subclasses
are inherited by other subclasses class_D and class_E respectively.

5. Hybrid Inheritance
Hybrid Inheritance, as the name suggests, is the combination of two or over two types of inheritances. For example,
the classes in a program are in such an arrangement that they show both single inheritance and hierarchical
inheritance at the same time. Such an arrangement is known as the Hybrid Inheritance. This is arguably the most
complex inheritance among all the types of inheritance in C++. The data members of the base class will be accessed
according to the specified visibility mode.

OOPS with C++ Mrs. Kirti Verma Page- 7


Syntax
class class_A
{
// class definition
};
class class_B
{
// class definition
};
class class_C: visibility_mode class_A, visibility_mode
class_B
{
// class definition
};
class class_D: visibility_mode class_C
{
// class definition
};
class class_E: visibility_mode class_C
{
// class definition
};
The derived class class_C inherits two base classes that are, class_A and class_B. This is the structure of Multiple
Inheritance. And two subclasses class_D and class_E, further inherit class_C. This is the structure of Hierarchical
Inheritance. The overall structure of Hybrid Inheritance includes more than one type of inheritance.

Virtual Base Class


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

Abstract Classes
In programming, an abstract class in C++ has at least one pure virtual function by definition. In other words,
a function that has no definition. The abstract class's descendants must define the pure virtual function; otherwise, the
subclass would become an abstract class in its own right. Abstract classes are used to express broad concepts from
which more concrete classes can be derived. An abstract class type object cannot be created. To abstract class types,
however, you can use pointers and references. We Declare at least one pure virtual member feature when creating an
abstract class. The pure specifier (= 0) syntax is used to declare a virtual function.
Syntax:
Class classname //abstract class
{
//data members
public:
//pure virtual function /* Other members */
};

Constructors In Derived Classes


Constructors in Derived Class in C++
In C++, constructors in derived classes are special member functions used to initialize objects of derived classes.
When an object is created of a derived class, its constructor is called to initialize both the base class part and the
derived class part of the object. Constructors in derived classes can call constructors of their base classes explicitly to
ensure proper initialization of the inherited members.
#include <iostream.h>
// Base class
class Base {
public:
Base() {
std::cout << "Base constructor\n";
}
};
// Derived class
class Derived : public Base {
public:
Derived() {
std::cout << "Derived constructor\n";
}
};

OOPS with C++ Mrs. Kirti Verma Page- 8


void main() {
Derived d; // Creating an object of the derived class
}
In this example, an object of the Derived class (Derived d;), its constructor is called. The constructor of the Derived
class implicitly calls the constructor of the Base class (Base()), ensuring that both the base class and the derived class
are properly initialized.

Nesting Of Class.
A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing
class and has the same access rights as the other members. However, the member functions of the enclosing class
have no special access to the members of a nested class.
#include<iostream.h>
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
void main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
}

OOPS with C++ Mrs. Kirti Verma Page- 9


UNIT –V
Pointers, virtual functions and polymorphism, pointers to objects, this pointer, pointers to derived class, pure virtual
functions, exception handling in C++, managing console I/O operations, working with files :open, close, basic read-
write operations on files .

Pointer
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare
a pointer before you can work with it. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable.
The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address. The only difference between pointers of different data types
is the data type of the variable or constant that the pointer points to.

This pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of
this keyword in C++.
• It can be used to pass current object as a parameter to another method.
• It can be used to refer current class instance variable.
• It can be used to declare indexers.
C++ this Pointer Example
#include <iostream.h>
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
void main(void) {
Employee e1 =Employee(101, "Kshitiz", 89000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
}
Pointer to derived class
In object-oriented programming, Pointer can be used for objects of base classes as well as objects of derived classes.
A pointer to a derived class refers to a pointer that points to an object of a derived class, which is a subclass that
inherits from a base class. The concept is based on inheritance, where a derived class inherits the properties and
behaviours (data members and member functions) of the base class.
by a pointer to a derived class, we can use it to access both the member functions and data members of the base
class and the additional ones defined in the derived class. This is one of the fundamental features of polymorphism,
as you can treat objects of the derived class as objects of the base class, allowing for code reusability and flexibility.

Pure Virtual Functions


Pure virtual functions are used if a function doesn't have any utility in the base class but the function must be
implemented by all its derived classes.
For example,
Suppose, we have derived Triangle, Square and Circle classes from the Shape class, and we want to calculate the
area of all these shapes. In this case, we can create a pure virtual function named calculateArea() in the Shape. Since
it's a pure virtual function, all derived classes Triangle, Square and Circle must include the calculateArea() function
with implementation. A pure virtual function doesn't have the function body and it must end with = 0.
class Shape {
public:

OOPS with C++ Mrs. Kirti Verma Page- 10


// creating a pure virtual function
virtual void calculateArea() = 0;
};
Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's just the way we define pure virtual functions.

// C++ program to calculate the area of a square and a circle


#include <iostream.h>
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cout<<”\n enter dimention: ”;
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
void main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
}

Exception handling in C++,


In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The
process of handling these exceptions is called exception handling. Using the exception handling mechanism, the
control from one part of the program where the exception occurred can be transferred to another part of the code.
So basically using exception handling in C++, we can handle the exceptions so that our program keeps running.
An exception is an unexpected problem that arises during the execution of a program our program terminates
suddenly with some errors/issues. Exception occurs during the running of the program (runtime).
There are two types of exceptions in C++
1. Synchronous: Exceptions that happen when something goes wrong because of a mistake in the input data or
when the program is not equipped to handle the current type of data it’s working with, such as dividing a number
by zero.
2. Asynchronous: Exceptions that are beyond the program’s control, such as disc failure, keyboard interrupts, etc.

try and catch


C++ provides an inbuilt feature for Exception Handling. It can be done using the following specialized keywords: try,
catch, and throw with each having a different purpose.
Syntax of try-catch in C++
try {
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 ) {
// catch block catches the exception that is thrown from try block
}
1. try in C++
The try keyword represents a block of code that may throw an exception placed inside the try block. It’s followed by
one or more catch blocks. If an exception occurs, try block throws that exception.

2. catch in C++

OOPS with C++ Mrs. Kirti Verma Page- 11


The catch statement represents a block of code that is executed when a particular exception is thrown from the try
block. The code to handle the exception is written inside the catch block.

3. throw in C++
An exception in C++ can be thrown using the throw keyword. When a program encounters a throw statement, then it
immediately terminates the current function and starts finding a matching catch block to handle the thrown exception.

Note: Multiple catch statements can be used to catch different type of exceptions thrown by try block.
The try and catch keywords come in pairs: We use the try block to test some code and If the code throws an exception
we will handle it in our catch block.

The main advantages of exception handling over traditional error handling:


• Separation of Error Handling Code from Normal Code: There are always if-else conditions to handle errors in
traditional error handling codes. These conditions and the code to handle errors get mixed up with the normal flow.
This makes the code less readable and maintainable. With try/catch blocks, the code for error handling becomes
separate from the normal flow.
• Functions/Methods can handle only the exceptions they choose: A function can throw many exceptions, but may
choose to handle some of them. The other exceptions, which are thrown but not caught, can be handled by the
caller. If the caller chooses not to catch them, then the exceptions are handled by the caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must
handle the exception in some way (either by specifying it again or catching it).

Grouping of Error Types: In C++, both basic types and objects can be thrown as exceptions. We can create a
hierarchy of exception objects, group exceptions in namespaces or classes, and categorize them according to their
types.
// C++ program to demonstrate the use of try,catch and throw in exception handling.
#include <iostream.h>
#include <stdexcept.h>
void main()
{
// try block
try {
int numerator = 10;
int denominator = 0;
int res;
// check if denominator is 0 then throw runtime error.
if (denominator == 0) {
throw runtime_error( "Division by zero not allowed!");
}
// calculate result if no exception occurs
res = numerator / denominator;
//[printing result after division
cout << "Result after division: " << res << endl;
}
// catch block to catch the thrown exception
catch (const exception& e) {
// print the exception
cout << "Exception " << e.what() << endl;
}
}

Managing console I/O operations,


Every program takes some data as input and generates processed data as an output following the familiar input
process output cycle. It is essential to know how to provide the input data and present the results in the desired form.
The use of the cin and cout is already known with the operator >> and << for the input and output operations. In this
article, we will discuss how to control the way the output is printed.

C++ supports a rich set of I/O functions and operations. These functions use the advanced features of C++ such as
classes, derived classes, and virtual functions. It also supports all of C’s set of I/O functions and therefore can be used
in C++ programs, but their use should be restrained due to two reasons.

I/O methods in C++ support the concept of OOPs.


I/O methods in C cannot handle the user-define data type such as class and object.
It uses the concept of stream and stream classes to implement its I/O operations with the console and disk files.

C++ Stream
The I/O system in C++ is designed to work with a wide variety of devices including terminals, disks, and tape drives.
Although each device is very different, the I/O system supplies an interface to the programmer that is independent of
the actual device being accessed. This interface is known as the stream.

A stream is a sequence of bytes.

OOPS with C++ Mrs. Kirti Verma Page- 12


• The source stream that provides the data to the program is called the input stream.
• The destination stream that receives output from the program is called the output stream.
• The data in the input stream can come from the keyboard or any other input device.
• The data in the output stream can go to the screen or any other output device.
C++ contains several pre-defined streams that are automatically opened when a program begins its execution. These
include cin and cout. It is known that cin represents the input stream connected to the standard input device (usually
the keyboard) and cout represents the output stream connected to the standard output device (usually the screen).

C++ Stream Classes


The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal with both the
console and disk files. These classes are called stream classes. The hierarchy of stream classes used for input and
output operations is with the console unit. These classes are declared in the header file iostream. This file should be
included in all the programs that communicate with the console unit.

Program to implement the usage of precision() function


#include <iostream,h>
#include<iomanip.h>
void main()
{
float PI=22.0/7.0;
int j;
cout<<"Value of pi :\n ";
for(j=0;j<=9;j++)
{
cout.width(j+1);
cout.precision(j);
cout<<PI<<"\n";
}
}
working with files :open, close, basic read-write operations on files .

File handling in C++ is a mechanism to store the output of a program in a file and help perform various operations on
it. Files help store these data permanently on a storage device.
file handling is further divided into sub-topics:
• Create a file
• Open a file
• Read from a file
• Write to a file
• Close a file
fstream library
Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file
handling method. In C++, fstream library is used to handle files, and it is dealt with the help of three classes known as
ofstream, ifstream and fstream.
1. ofstream:This class helps create and write the data to the file obtained from the program’s output. It is also known
as the input stream.
2. ifstream:We use this class to read data from files and also known as the input stream.
3. fstream:This class is the combination of both ofstream and ifstream. It provides the capability of creating, writing
and reading a file.
To access the following classes, we must include the fstream as a header file like how we declare iostream in the
header.
#include <fstream.h>
#include <iostream.h>
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("myfile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore(); // clear buffer and again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("myfile.dat");
cout << "Reading from the file" << endl;

OOPS with C++ Mrs. Kirti Verma Page- 13


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

OOPS with C++ Mrs. Kirti Verma Page- 14

You might also like