0% found this document useful (0 votes)
8 views18 pages

c++ Programming Notes (Unit-4)

The document provides notes on C++ programming, specifically focusing on Unit 4 topics such as static members, interfaces, exception handling, and stream classes. It explains concepts like static member variables and functions, abstract classes, exception handling mechanisms using try, catch, and throw, and the use of input/output streams in C++. Code examples illustrate each concept to enhance understanding for BCA 2nd year students at Aishwarya College of Education.

Uploaded by

RamPrasad Saran
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)
8 views18 pages

c++ Programming Notes (Unit-4)

The document provides notes on C++ programming, specifically focusing on Unit 4 topics such as static members, interfaces, exception handling, and stream classes. It explains concepts like static member variables and functions, abstract classes, exception handling mechanisms using try, catch, and throw, and the use of input/output streams in C++. Code examples illustrate each concept to enhance understanding for BCA 2nd year students at Aishwarya College of Education.

Uploaded by

RamPrasad Saran
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/ 18

AISHWARYA COLLEGE OF EDUCATION

DEPARTMENT: COMPUTER SCIENCE


FACULTY NAME: SUMIT PUROHIT

Course BCA
Class BCA 2nd YEAR
Subject C++ PROGRAMMING
Unit 4

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 1


C++ PROGRAMMING NOTES: UNIT-4

TABLE OF CONTENT

SNO TOPICS
1. STATIC MEMBERS
2. INTERFACES
3. EXCEPTION HANDLING
4. STREAM CLASSES

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 2


C++ PROGRAMMING NOTES: UNIT-4

1. STATIC MEMBERS

Static member variable:


When a member variable is declare as static:
It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
It is visible only within the class, but its life time is the entire program.
Static variable are commonly used to maintain values common to entire class.
#include<iostream.h>
#include<conio.h>
class demo
{
static int count;
int num;
public:
void getdata(int a)
{
num = a;
count++;
}
void getcount()
{
cout<<"count: ";
cout<<count<<"\n";
}
};
int demo::count;
void main()
{
demo a,b,c;
clrscr();
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 3


C++ PROGRAMMING NOTES: UNIT-4

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

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 4


C++ PROGRAMMING NOTES: UNIT-4

a.set();
b.set();
demo:: showcount();
demo c;
c.set();
demo :: showcount();
a.show();
b.show();
c.show();
getch();
}

Differences between Static Member Function and Non-Static


Member Functions
The differences between a static member function and non-static member functions
are as follows.
1. A static member function can access only static member data, static member
functions and data and functions outside the class. A non-static member
function can access all of the above including the static data member.
2. A static member function can be called, even when a class is not instantiated,
a non-static member function can be called only after instantiating the class
as an object.
3. A static member function cannot be declared virtual, whereas a non-static
member functions can be declared as virtual.
4. A static member function cannot have access to the 'this' pointer of the class.
5. The static member functions are not used very frequently in programs. But
nevertheless, they become useful whenever we need to have functions which
are accessible even when the class is not instantiated.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 5


C++ PROGRAMMING NOTES: UNIT-4

2. INTERFACES

An interface describes the behavior or capabilities of a C++ class without


committing to a particular implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract
classes should not be confused with data abstraction which is a concept of keeping
implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure
virtual function. A pure virtual function is specified by placing "= 0" in its
declaration as follows −
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;

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

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 6


C++ PROGRAMMING NOTES: UNIT-4

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

class Triangle: public Shape {


public:
int getArea() {
return (width * height)/2;
}
};

int main(void) {
Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);
PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 7
C++ PROGRAMMING NOTES: UNIT-4

// Print the area of the object.


cout << "Total Triangle area: " << Tri.getArea() << endl;

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.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 8


C++ PROGRAMMING NOTES: UNIT-4

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 −

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 9


C++ PROGRAMMING NOTES: UNIT-4

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

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;

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 10


C++ PROGRAMMING NOTES: UNIT-4

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!

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 11


C++ PROGRAMMING NOTES: UNIT-4

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.

 Input Stream: If the direction of flow of bytes is from the device(for


example, Keyboard) to the main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.

Header files available in C++ for Input/Output operations are:


1. iostream: iostream stands for standard input-output stream. This header
file contains definitions to objects like cin, cout, cerr etc.
2. iomanip: iomanip stands for input output manipulators. The methods
declared in this files are used for manipulating streams. This file contains
definitions of setw, setprecision etc.
3. fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being written
into the file as output.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 12


C++ PROGRAMMING NOTES: UNIT-4

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;

cout << "Enter your age:";


cin >> age;
cout << "\nYour age is: " << 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

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 14


C++ PROGRAMMING NOTES: UNIT-4

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

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 15


C++ PROGRAMMING NOTES: UNIT-4

Open a file for writing.


5 ios::trunc
If the file already exists, its contents will be truncated before opening the
file.
You can combine two or more of these values by ORing them together. For example
if you want to open a file in write mode and want to truncate it in case that already
exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows

fstream afile;
afile.open("file.dat", ios::out | ios::in );

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.

Reading from a File


You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of
the cin object.

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 16


C++ PROGRAMMING NOTES: UNIT-4

Read and Write Example


Following is the C++ program which opens a file in reading and writing mode. After
writing information entered by the user to a file named afile.dat, the program reads
information from the file and outputs it onto the screen −

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

File Position Pointers


Both istream and ostream provide member functions for repositioning the file-
position pointer. These member functions are seekg ("seek get") for istream
and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument
can be specified to indicate the seek direction. The seek direction can
be ios::beg (the default) for positioning relative to the beginning of a
stream, ios::cur for positioning relative to the current position in a stream
or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a
number of bytes from the file's starting location. Some examples of positioning the
"get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );

PREPARED BY: SUMIT PUROHIT, ASST. PROFESSOR, AISHWARYA COLLEGE Page 18

You might also like