OOPs Unit5 Preeti
OOPs Unit5 Preeti
C++ Exceptions
When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The
technical term for this is: C++ will throw an exception (throw an error).
The try statement allows you to define a block of code to be tested for errors while it
is being executed.
The throw keyword throws an exception when a problem is detected, which lets us
create a custom error.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Example
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Example
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Example:
#include <iostream>
using namespace std;
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run above code,
this would produce the following result −
Division by zero condition!
Templates:
Templates in C++ is an interesting feature that is used for generic programming and
templates in c++ is defined as a blueprint or formula for creating a generic class or a
function. Simply put, you can create a single function or single class to work with
different data types using templates.
C++ template is also known as generic functions or classes which is a very powerful
feature in C++. A keyword “template” in c++ is used for the template’s syntax and
angled bracket in a parameter (t), which defines the data type variable.
• Function template
• Class templates
A function template in c++ is a single function template that works with multiple data
types simultaneously, but a standard function works only with one set of data types.
Here, type is a placeholder name for a data type used by the function. It is used within
the function definition.
Source Code:
#include<iostream.h>
using namespace std;
template<classX>//can replace 'class" keyword by "typename" keyword
X func( Xa,Xb)
{
return a;
}
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output
15
7.5
You’ve seen how a member function is defined within a class template. Now, alternatively, it
is also possible for the template member function to be defined independently of the
declaration of its class template.
The compiler will use the template arguments that you used, in this case, to create the class
template when you call a member function of a class template specialization. The following
illustration exemplifies this:
Example:
#include<iostream>
using namespace std;
template<class A> class B {
public:
A operator+(A);
};
int main() {
B<char> ob1;
B<int> ob2;
cout<< ob1 +'p' << endl;
cout<< ob2 + 10;
return 0;
}
Output:
10
We can make a simple Calculator performing the four basic arithmetic operations in
C++ using a class template. The template of the class will consist of two variables
whose values are passed at the time of object creation. The constructor of this class
takes two arguments of generic datatypes. Further, you will see, this Calculator class
template consists of five main functions – show(), addition(), subtraction(),
multiplication(), and division(). The show() function is responsible for calling the rest
of the four generic functions. Moving ahead, we have created two instances from the
template of Calculator class and performed the basic calculations using its class
functions.
Example:
public:
Calculator(Temp num1, Temp num2)
{
n1 = num1;
n2 = num2;
}
void show()
{
cout << "Addition is: " << n1 << "+" << n2 << "=" << addition() << endl;
cout << "Subtraction is: " <<n1 << "-" << n2 << "=" << subtraction() <<
endl;
cout << "Product is: " << n1 << "*" << n2 << "=" << multiplication() <<
endl;
cout << "Division is: " << n1 << "/" << n2 << "=" << division() << endl;
}
int main()
{
Calculator<int> Calc1(25, 12);
Calculator<float> Calc2(13.6, 5.9);
cout << endl << "Float results for 13.6 and 5.9:" << endl;
Calc2.show();
return 0;
}
Output
C++ Class Templates With Multiple Parameters
It is possible to provide more than one type when generating templates. A class template can
have many generic data types. They are listed in a comma-delimited format as shown in the
following example.
Example:
#include<iostream>
using namespace std;
// Class template with more than one parameter
template<class Temp1, class Temp2>
class Sample
{
Temp1 l;
Temp2 m;
public:
Sample(Temp1 a, Temp2 b)
{
l = a;
m = b;
}
void display()
{
cout << "The inputs are: " <<l << " and " << m << endl;
}
};
// Driver function
int main()
{
// instantiation
Sample <int, char> ob1 (24, 'A');
// instantiation
Sample<int, float> ob2(22.56, 34.9);
Output:
As seen in the above cited example, we can use more than one parameter for a
template in C++. Here, the template Temp takes two parameters, both of the Sample
class type, separated by a comma. Moreover, the constructor of the Sample class takes
two arguments of generic datatype. When we create objects, the types of arguments
are specified in angular brackets (< >). In case of multiple parameters, the datatypes
are also separated by commas. The constructor is called at the time when objects are
created, and template arguments receive values.
template<class Ttype>
class class_name
{
//class body;
}
Here Type is a placeholder type name, which will be specified when a class instantiated.
The Type can be used inside the body of the class.
Class template in c++ example:
Source Code:
#include<iostream.h>
using namespace std;
template <class C>
class A{
private;
C,a,b;
public:
A(Cx,Cy){
a=x;
b=y;
}
void show()
}
count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;
}
C add(){
C c=a+b;
return c;
}
};
int main(){
Aaddint(8,6);
Aaddfloat(3.5,2.6);
Aaaddouble(2.156,5.234);
Aaddint.show();
cout<<endl;
adddouble.show();
count<<endl;
return 0;
}
Output
File Handling:
Files are used to store data in a storage device permanently. File handling provides a
mechanism to store the output of a program in a file and to perform various operations
on it.
In C++ we have a set of file handling methods. These include ifstream, ofstream, and
fstream. These classes are derived from fstrembase and from the corresponding
iostream class. These classes, designed to manage the disk files, are declared in fstream
and therefore we must include fstream and therefore we must include this file in any
program that uses files.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
• ofstream: This Stream class signifies the output file stream and is applied to
create files for writing information to files
• ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
• fstream: This Stream class can be used for both read and write from/to files.
All the above three classes are derived from fstreambase and from the corresponding
iostream class and they are designed specifically to manage disk files.
C++ provides us with the following operations in File Handling:
Opening a File
Generally, the first operation performed on an object of one of these classes is to
associate it to a real file. This procedure is known to open a file.
open() function
Syntax
The second argument represents the mode in which the file has to be opened. The
following modes are used as per the requirements.
Modes Description
Opens the file to read(default for
In
ifstream)
Opens the file to write(default for
Out
ofstream)
Binary Opens the file in binary mode
Opens the file and appends all the
app
outputs at the end
Opens the file and moves the control to
ate
the end of the file
trunc Removes the data in the existing file
nocreate Opens the file only if it already exists
Opens the file only if it does not already
noreplace
exist
Example
fstream new_file;
new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a
class so we need to create an object of this class to use its member functions. So we
create new_file object and call open() function. Here we use out mode that allows us to
open the file to write in it.
Example
ofstream new_file;
As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of the
file.
Using a stream insertion operator << we can write information to a file and using stream
extraction operator >> we can easily read information from a file.
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
Output:
Explanation
In the above example we first create an object to class fstream and name it ‘new_file’.
Then we apply the open() function on our ‘new_file’ object. We give the name
‘new_file’ to the new file we wish to create and we set the mode to ‘out’ which allows
us to write in our file. We use a ‘if’ statement to find if the file already exists or not if it
does exist then it will going to print “File creation failed” or it will gonna create a new
file and print “New file created”.
Writing to a File
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to file
new_file.close();
}
return 0;
}