c++ Programming Notes (Unit-4)
c++ Programming Notes (Unit-4)
Course BCA
Class BCA 2nd YEAR
Subject C++ PROGRAMMING
Unit 4
TABLE OF CONTENT
SNO TOPICS
1. STATIC MEMBERS
2. INTERFACES
3. EXCEPTION HANDLING
4. STREAM CLASSES
1. STATIC MEMBERS
c.getdata(300);
cout<<"after reading data:"<<"\n";
a.getcount();
b.getcount();
c.getcount();
getch();
}
Static member functions:
Like static member variables, static member functions are there in a particular
class. The static member function can have access to only other static members
(variable/ functions) declared in the same class. A static member function can be
called using the class name like:
Class name :: function name;
#include<iostream.h>
#include<conio.h>
class demo
{
int code;
static int count;
public:
void set()
{
code=++count;
}
void show()
{
cout<<"object number:"<<code<<"\n";
}
static void showcount()
{
cout<<"count: "<<count<<"\n";
}
};
int demo :: count;
void main()
{
demo a,b;
clrscr();
a.set();
b.set();
demo:: showcount();
demo c;
c.set();
demo :: showcount();
a.show();
b.show();
c.show();
getch();
}
2. INTERFACES
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot
be used to instantiate objects and serves only as an interface. Attempting to
instantiate an object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of
the virtual functions, which means that it supports the interface declared by the
ABC. Failure to override a pure virtual function in a derived class, then attempting
to instantiate objects of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
Abstract Class Example
Consider the following example where parent class provides an interface to the base
class to implement a function called getArea() −
// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
Tri.setWidth(5);
Tri.setHeight(7);
PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 7
C++ PROGRAMMING NOTES: UNIT-4
return 0;
}
When the above code is compiled and executed, it produces the following result –
Total Rectangle area: 35
Total Triangle area: 17
You can see how an abstract class defined an interface in terms of getArea() and two
other classes implemented same function but with different algorithm to calculate
the area specific to the shape.
An object-oriented system might use an abstract base class to provide a common
and standardized interface appropriate for all the external applications. Then,
through inheritance from that abstract base class, derived classes are formed that
operate similarly.
The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations
of these pure virtual functions are provided in the derived classes that correspond to
the specific types of the application.
This architecture also allows new applications to be added to a system easily, even
after the system has been defined.
3. EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the
code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.
Following is an example of throwing an exception when dividing by zero condition
occurs −
Catching Exceptions
The catch block following the try block catches any exception. You can specify what
type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify
that a catch block should handle any type of exception that is thrown in a try block,
you must put an ellipsis, ..., between the parentheses enclosing the exception
declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch
it in catch block.
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
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!
4. STREAM CLASSES
C++ comes with libraries which provides us with many ways for performing input
and output. In C++ input and output is performed in the form of a sequence of bytes
or more commonly known as streams.
The two keywords cout in C++ and cin in C++ are used very often for printing
outputs and taking inputs respectively. These two are the most basic methods of
taking input and printing output in C++. To use cin and cout in C++ one must
include the header file iostream in the program.
Standard output stream (cout): Usually the standard output device is the
display screen. The C++ cout statement is the instance of the ostream class. It is
used to produce output on the standard output device which is usually the display
screen. The data needed to be displayed on the screen is inserted in the standard
output stream (cout) using the insertion operator(<<).
int main()
{
char sample[] = "aishwaryacollege";
cout << sample << " - A computer science portal for students";
return 0;
}
In the above program the insertion operator(<<) inserts the value of the string
variable sample followed by the string “A computer science portal for students” in
the standard output stream cout which is then displayed on screen.
standard input stream (cin): Usually the input device in a computer is the
keyboard. C++ cin statement is the instance of the class istream and is used to
read input from the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs.
The extraction operator extracts the data from the object cin which is entered using
the keboard.
int main()
{
int age;
return 0;
}
Input :
PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 13
C++ PROGRAMMING NOTES: UNIT-4
18
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is connected to the
input device. The age entered by the user is extracted from cin using the extraction
operator(>>) and the extracted data is then stored in the variable age present on
the right side of the extraction operator.
Un-buffered standard error stream (cerr): The C++ cerr is the standard error
stream which is used to output the errors. This is also an instance of the iostream
class. As cerr in C++ is un-buffered so it is used when one needs to display the error
message immediately. It does not have any buffer to store the error message and
display later.
int main()
{
cerr << "An error occured";
return 0;
}
Output:
An error occured
buffered standard error stream (clog): This is also an instance of iostream class
and used to display errors but unlike cerr the error is first inserted into a buffer and
is stored in the buffer until it is not fully filled. The error message will be displayed
on the screen too.
int main()
{
clog << "An error occured";
return 0;
}
Output:
An error occured
File Stream
So far, we have been using the iostream standard library, which
provides cin and cout methods for reading from standard input and writing to
standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another
standard C++ library called fstream, which defines three new data types −
Sr.No Data Type & Description
1 ofstream
This data type represents the output file stream and is used to create files
and to write information to files.
2 ifstream
This data type represents the input file stream and is used to read
information from files.
3 fstream
This data type represents the file stream generally, and has the capabilities
of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And
ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and
the second argument of the open() member function defines the mode in which the
file should be opened.
Sr.No Mode Flag & Description
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
3 ios::in
Open a file for reading.
4 ios::out
Closing a File
When a C++ program terminates it automatically flushes all the streams, release
all the allocated memory and close all the opened files. But it is always a good
practice that a programmer should close all the opened files before program
termination.
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program
using the stream insertion operator (<<) just as you use that operator to output
information to the screen. The only difference is that you use
an ofstream or fstream object instead of the cout object.
#include <fstream.h>
#include <iostream.h>
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.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();
// 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("afile.dat");
cout << "Reading from the file" << endl;
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();
return 0;
}
PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 17
C++ PROGRAMMING NOTES: UNIT-4
When the above code is compiled and executed, it produces the following sample
input and output −
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline()
function to read the line from outside and ignore() function to ignore the extra
characters left by previous read statement.