Unit 3 - Mahalakshmi Engineering College

advertisement
QUESTION BANK
DEPARTMENT:EEE
SEMESTER: V
SUBJECT CODE / Name: CS2311 – OBJECT ORIENTED PROGRAMMING
UNIT – III
PART - A (2 Marks)
1. What are the advantages of using exception handling? (AUC MAY 2013)
In C++, exception handling is useful because it makes it easy to separate the error handling
code from the code written to handle the chores of the program. Doing so makes reading and
writing the code easier.
C++ uses to handle exceptions means that it can easily handle those exceptions without any
code in the intermediate functions.
2. What is Standard Template Library? State its purpose. (AUC MAY 2013, DEC 2010)
A collection of generic classes and functions is called the Standard Template Library.
STL components are part of C++ standard library.
It provides many of the basic algorithms and data structures of computer science.
The STL is a generic library, meaning that its components are heavily parameterized: almost
every component in the STL is a template.
3. What is a namespace? State the purpose of namespaces with example (AUC DEC
2012, MAY 2012)
ANSI C++ Standard has added a new keyword namespace to define a scope that could hold
global identifiers. The best example of namespace scope is the C++ Standard Library.All classes,
functions and templates are declared within the namespace named std.
Using namespace std;
The using namespace statement specifies that the members defined in std namespace will
be used frequently throughout the program.
The namespace is useful in the case that there is a possibility that a global object or function
1
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
1
uses the same identifier as another one, causing redefinition errors.
4. What is the difference between throw and throws? (AUC DEC 2012)
Throw is used to actually throw the exception, whereas throws is declarative for the method.
They are not interchangeable.
Throws: this is to be used when you are not using the try catch statement in your code but
you know that this particular class is capable of throwing so and so exception(only checked
exceptions). In this you do not use try catch block but write using the throw clause at
appropriate point in your code and the exception is thrown to caller of the method and is
handled by it.
5. Define exception. Give example.(AUC MAY 2012)
Exceptions which occur during the program execution, due to some fault in the input data.
Example: Array limit exceeding, division by zero.
Exceptions are classifieds into
a)Synchronous exception
b) Asynchronous exception
6. What are manipulators? How do you create a one? (AUC DEC 2011)
The header file iomanip provides a set of functions called manipulators which can be used to
manipulate the output formats. They provide same features as that of the ios member
functions and flags.
Ex:
setw(5); - to set the width of size 5 bytes.
7. What is the difference between a function template and template function? (AUC
DEC 2011)
The term “function template” refers to a kind of template. The term “template function” is
sometimes used to mean the same thing, and sometimes to mean a function instantiated from a
function template.
The “template function” is also called as “instance of a function template”.
8. What are IO streams? Give an example. (AUC DEC 2010)
A Stream is a sequence of bytes. It can either as a source from which the input data can be
obtained or as a destination to which the output data can be sent.
The stream source that provides data to the program is called the input stream and the
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
2
destination stream that receives output from the program is called output stream.
9. List the containers supported by Standard Template Library.
The STL contains three types of containers
1) Sequence containers
2) Associative containers
3) Derived containers
10. List some of the file modes.
1)ios::in
2)ios::out
3)ios::ate
4)ios::app
5)ios::trunk
6)ios::nocreate
7)ios::noreplace
8)ios::binary
11. Compare the performance characteristics of 3 containers.
12. What is container?
A container is an object that actually stores data. It is a way data is organized in memory.
The STL containers are implemented by template classes and therefore can be easily customized
to hold different types of data
13. What is an iterator?
An iterator is an object that points to an element in a container. We can use iterators to
move through the contents of containers. Iterators are handled just like pointers
14. Define vector and list.
The vector stores elements in contiguous memory locations and enables direct access to any
element using the subscript operator[]. A vector can change its size dynamically and therefore
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
3
allocates memory as needed at run time
The list is another container that is popularly used. It supports a bidirectional, linear list and
provides an efficient implementation for deletion and insertion operations.
15. What are the types of derived containers?
The STL provides three types of derived containers
1) Stack
2) Queue
3) Priority queue
16. What are 3 basic keywords of exception handling mechanism?
 Try - try for indicating program area where exception can be thrown.
 Throw – for throwing an exception.
 Catch – catch for actually taking an action for the specific exception.
17. List out some of the unformatted I/O operators and formatted I/O operations.
Unformatted:
a)put()
b)get()
c)getline()
d)write()
Formatted:
a)ios stream class member functions and flags
b)Standard manipulators
c)User –defined manipulators
18. List out some of the manipulators.
a)setw(int width)
b)setprecision(int prec)
c)setfill(int fchar)
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
4
d)setbase(int base)
e)setiosflags(long flags)
f)resetioflags(long flags)
19. What are the functions that the file stream class provides?
a)seekg()-Moves get pointer to a specified location
b)seekp()-Moves put pointer to a specified location
c)tellg()-Gives the current position of the get pointer
d)tellp()-Gives the current position of the put pointer
20. What is unnamed namespaces?
An unnamed namespace is one that does not have a name. Unnamed namespace members
occupy global scope and are accessible in all scopes following the declaration in the file
PART – B (16 Marks)
1. (i) What are the various ways of handling exceptions? When do we use multicatch handlers? Explain with an example. (8) (AUC MAY 2013)
Exception handling is a mechanism that separates code that detects and handles
exceptional circumstances from the rest of your program. Note that an exceptional
circumstance is not necessarily an error.
When a function detects an exceptional situation, you represent this with an object.
This object is called an exception object. In order to deal with the exceptional situation you
throw the exception. This passes control, as well as the exception, to a designated block of
code in a direct or indirect caller of the function that threw the exception. This block of code
is called a handler. In a handler, you specify the types of exceptions that it may process. The
C++ run time, together with the generated code, will pass control to the first appropriate
handler that is able to process the exception thrown. When this happens, an exception is
caught. A handler may rethrow an exception so it can be caught by another handler.
The exception handling mechanism is made up of the following elements:
try blocks
catch blocks
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
5
throw expressions
Multiple Catch statements
(ii)Draw the I/O stream hierarchy in C++ and explain it clearly. (8) (AUC MAY
2013)
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
6
2. (i) Write a C++ program to compute the square root of a number. The input value must
be tested for validity. If it is negative, the user defined function mysqrt() should raise
an exception. (8) (AUC MAY 2013)
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
7
(ii)Explain the following functions (with example) for manipulating file pointers:
seekg(), seekp(), tellg(), tellp(). (8) (AUC MAY 2013)
Functions for manipulation of file pointers:
seekg() - Moves get pointer (input) to a specified location.
seekp() - Moves put pointer (output) to a specified location.
tellg() - Gives the current position of the get pointer.
tellp() - Gives the current position of the put pointer.
For example,
infile.seekg(10);
Example program:
#include <iostream>
#include <fstream>
using namespace std;
void main(void)
{
char filename[ ] = "C:\\amad\\testfileio3.txt";
fstream inputfile, outputfile;
int length;
char* buffer;
// create, open and write data to file
outputfile.open(filename, ios::out);
// simple error handling
if(inputfile.fail())
{
cerr<<"The file "<<filename<<" could not be created/opened!\n";
exit(1);
}
// test if successful to close the file
else
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
8
cout<<"The "<<filename<<" file was opened successfully!\n";
// write some text
cout<<"Writing some text to the output file..."<<endl;
outputfile<<"This is just line of text as a simple file content. This is testfileio3.txt file"<<endl;
// close the output file
cout<<"Closing the output file..."<<endl;
outputfile.close();
// opening and reading data from file
cout<<"Opening the input file..."<<endl;
inputfile.open(filename, ios::in);
// simple error handling for files creating/opening for writing
if(inputfile.fail())
{
cout<<"Opening "<<filename<<" file for reading\n";
cout<<"------------------------------------------\n";
cerr<<"The file "<<filename<<" could not be created/opened!\n";
cerr<<"Possible errors:\n";
cerr<<"1. The file does not exist.\n";
cerr<<"2. The path was not found.\n";
exit(1); // just exit
// 0-normal, non zero - some errors
}
else
{
cout<<"The "<<filename<<" file was opened successfully!\n";
cout<<"\nMove the pointer to the end\n"
<<"Then back to the beginning with\n"
<<"10 offset. The pointer now at...\n"<<endl;
// flush the stream buffer explicitly
cout<<flush;
// get length of file, move the get pointer to the end of the stream
inputfile.seekg(0, ios::end);
// The tellg() member function returns the current stream position.
length = inputfile.tellg();
cout<<"string length = "<<length<<"\n";
// dynamically allocate some memory storage for type char
buffer = new char[length];
// move back the pointer to the beginning with offset of 10 (skips 10 char)
inputfile.seekg(10, ios::beg);
// read data as block from input file
inputfile.read(buffer, length);
cout<<buffer<<endl;
// free up the allocated memory storage
delete [ ] buffer;
// close the input file
inputfile.close();
}
return;
}
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
9
Output example:
The C:\amad\testfileio3.txt file was opened successfully!
Writing some text to the output file...
Closing the output file...
Opening the input file...
The C:\amad\testfileio3.txt file was opened successfully!
Move the pointer to the end
Then back to the beginning with
10 offset. The pointer now at...
string length = 82
3. Explain file handling techniques in cpp. (AUC DEC 2012, MAY 2012)
Many real-life problems handle large volumes of data, therefore we need to use
some devices such as floppy disk or hard disk to store the data. The data is stored in these
devices using the concept of files. A file is a collection of related data stored in a particular
area on the disk. Programs can be designed to perform the read and write operations on
these files. A program typically involves either or both of the following kinds of data
communication:
Data transfer between the console unit and the program.
Data transfer between the program and a disk file.
The input/output system of C++ handles file operations which are very much
similar to the console input and output operations.
It uses file streams as an interface between the programs and the files. The
stream that supplies data to the program is known as input stream and the one that
receives data from the program is known as output stream.
In other words, the input stream extracts or reads data from the file and the output
stream inserts or writes data to the file.
Classes for the file stream operations
The I/O system of C++ contains a set of classes that define the file handling
methods.
These include ifstream, ofstream and fstream.
These classes, designed to manage the disk files, are declared in fstream.h and
therefore we must include this file in any program that uses files.
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
10
filebuf
Its purpose is to set the file buffer to read and write. Contains openprot
constant used in the open() of the filestream classes. Also contains close() and open() as
member functions.
fstreambase
Provides operations common to the file streams. Serves as a base for fstream,
ifstream and ofstream classes. Contains open() and close() functions.
ifstream
Provides input operations. Contains open() with default input mode. Inherits the
functions get(), getline(), read(), seekg() and tellg() functions from istream.
ofstream
Provides output operations. Contains open() with default output mode. Inherits
put(), seekp(), tellp(), and write() functions from ostream.
fstream
Provides support for simultaneous input and output operations. Contains open()
with default input mode. Inherits all the functions from istream and ostream classes through
iostream.
The ifstream, ofstream and fstream classes are declared in the file fstream.h The
istream and ostream classes are also included in the fstream.h file.
Opening and closing a file
For opening a file, we must first create a file stream and than link it to the filename.
A filestream can be defined using the classes ifstream, ofstream, and fstream that are
contained in the header file fstream.h
A file can be opened in two ways:
Using the constructor function of the class. This method is useful when we open only
one file in the stream.
Using the member function open() of the class. This method is used when we want
to manage multiple files using one stream.
Using Constructor
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
11
Create a file stream object to manage the stream using the appropriate class. That
is, the class ofstream is used to create the output stream and the class ifstream to create the
input stream.
Initialize the file object with the desired filename,
e.g.: ofstream outfile(“sample.txt”);
The above statement creates an object outfile of class ofstream that manages the
output stream. This statement also opens the file sample.txt and attaches it to the output
stream for writing. Similarly, the statement declared in as an ifstream object and attaches to
the file “sample.txt” for reading.
ifstream infile(“sample.txt”);
Program: Writing and reading data into file, using constructors
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
12
To write data into the file, character by character
Writing and reading Objects of a class :
So far we have done I/O of basic data types. Since the class objects are the central
elements of C++ programming, it is quite natural that the language supports features for
writing and reading from the disk files objects directly.
The binary input and output functions read() and write() are designed to do exactly
this job.
The write() function is used to write the object of a class into the specified file and
read() function is used to read the object of the class from the file.
Both these functions take two arguments:
1. address of object to be written.
2. size of the object.
The address of the object must be cast to the type pointer to char.
One important point to remember is that only data members are written to the disk file and
the member functions are not.
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
13
Writing an object into the file
fstream object can be used for both input & output.
In the open() function we include several mode bits to specify certain aspects of the
file object. app -> To preserve whatever was in the file before. Whatever we write to the file
will be appended to the existing contents. We use in and out because we want to perform
both input and output on the file.
eof() is a member function of ios class. It returns a nonzero value if EOF is
encountered and a zero otherwise.
Functions for manipulation of file pointers:
seekg() - Moves get pointer (input) to a specified location.
seekp() - Moves put pointer (output) to a specified location.
tellg() - Gives the current position of the get pointer.
tellp() - Gives the current position of the put pointer.
4. Explain the different types of streams and various formatted I/O.(AUC MAY
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
14
2012)
Formatted I/O
C++ supports a number of features that could be used for formatting the output. They
include:
ios class functions and flags
manipulators
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
15
user-defined output functions
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
16
Designing our own manipulators:
The general form for creating a manipulator without any argument is:
ostream & manipulator(ostream & output)
{
……
……(code)
……
return output;
}
Example
ostream & unit(ostream output)
{
output<<” –inches-”;
return output;
}
The statement
cout<<36<<unit;
will produce the following output
36 –inches5. (i) Explain the features of I/O system supported in C++. (10) (AUC DEC 2011)
[Refer Q.No 1]
(ii) Write a program containing a possible exception. Use a try block and throw
it and a catch block to handle it properly. (6) (AUC DEC 2011)
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
17
6. (i) Write a program that reads a name from the keyboard into three separate
string objects and then concatenates them into a new string object using ‘+’
operator and append() function. (10) (AUC DEC 2011)
#include<iostream.h>
#include<string.h>
using namespace std;
void main(void)
{
char *s1,*s2,*s3;
char *fullstring;
cout<<”Enter three strings:”;
cin>>s1>>s2>>s3;
18
CS2311 OBJECT
OBJECT ORIENTED
ORIENTED PROGRAMMING
PROGRAMMING -- V
V Sem
Sem EEE
EEE – M.Sathya Asst.Prof./CSE18
CS2311
fullstring.assign(s1);
fullstring.append(“+”);
strcat(fullstring, s2);
fullstring.append(“+”);
strcat(fullstring,s3);
cout<<”Full string is:”;
cout<<fullstring;
}
OUTPUT
Enter three strings
One
Two
Three
Full string is: One+Two+Three
(ii) List the major categories of containers supported by STL. (6) (AUC DEC
2011)
19
CS2311 OBJECT
OBJECT ORIENTED
ORIENTED PROGRAMMING
PROGRAMMING -- V
V Sem
Sem EEE
EEE – M.Sathya Asst.Prof./CSE19
CS2311
7. Write a C++ program to demonstrate file handling as follows : get strings as
input from the user, store them in a file, retrieve them and display them. (AUC
DEC 2010)
20
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
8. Explain the exception handling mechanism available in C++ with suitable
examples. (AUC DEC 2010)
Exceptions are run time anomalies. They include conditions like division by zero or
access to an array outside to its bound etc.
Types:
Synchronous exception
Asynchronous exception.
· Find the problem ( Hit the exception )
· Inform that an error has occurred. (Throw exception)
· Receive error information (Catch exception)
· Take corrective action (Handle exception)
C++ exception handling mechanism is basically built upon three keywords, namely,
try , throw and catch. The keyword try is used to preface a block of statements which may
generate exceptions. This block of statements is known as try block. When an exception is
detected it is thrown using a throw statement in the try block. A catch block defined by the
keyword catch catches the exception thrown by the throw statement in the try block and
handles
it
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE
appropriately.
21
22
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
9. Explain namespaces with example.
One of C++'s less heralded additions is addition of namespaces, which can be used to
structure a program into "logical units". A namespace functions in the same way that a
company division might function -- inside a namespace you include all functions appropriate
for fulfilling a certain goal. For instance, if you had a program that connected to the Internet,
you might have a namespace to handle all connection functions:
namespace net_connect
{
int make_connection();
int test_connection();
//so forth...
}
23
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
You can then refer to functions that are part of a namespace by prefixing the function with
the namespace name followed by the scope operator -- ::. For instance,
net_connect::make_connection()
By enabling this program structure, C++ makes it easier for you to divide up a program into
groups that each perform their own separate functions, in the same way that classes or structs
simplify object oriented design.
But namespaces, unlike classes, do not require instantiation; you do not need an object to
use a specific namespace. You only need to prefix the function you wish to call with
namespace_name:: -- similar to how you would call a static member function of a class.
Another convenience of namespaces is that they allow you to use the same function name, when it
makes sense to do so, to perform multiple different actions. For instance, if you were implementing
a low-level IO routine and a higher level IO routine that uses that lower level IO, you might want to
have the option of having two different functions named "input" -- one that handles low-level
keyboard IO and one that handles converting that IO into the proper data type and setting its value
to a variable of the proper type.
So far, when we've wanted to use a namespace, we've had to refer to the functions within the
namespace by including the namespace identifier followed by the scope operator. You can,
however, introduce an entire namespace into a section of code by using a using-directive with the
syntax
using namespace namespace_name;
Doing so will allow the programmer to call functions from within the namespace without
having to specify the namespace of the function while in the current scope. (Generally, until the next
closing bracket, or the entire file, if you aren't inside a block of code.) This convenience can be
abused by using a namespace globally, which defeats some of the purpose of using a namespace. A
common example of this usage is
using namespace std;
which grants access to the std namespace that includes C++ I/O objects cout and cin.
Finally, you can introduce only specific members of a namespace using a using-declaration
with the syntax
using namespace_name::thing;
One trick with namespaces is to use an unnamed namespace to avoid naming conflicts. To
24
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
do so, simply declare a namespace with the normal syntax, but leave off the identifier; when this is
done, you will have
namespace
{
//functions
}
and within the namespace you are assured that no global names will conflict because each
namespace's function names take precedence over outside function names.
Now, you might ask, how can you actually use anything in that namespace? When your
program is compiled, the "anonymous" namespace you have created will be accessible within the
file you created it in. In effect, it's as though an additional "using" clause was included implicitly. This
effectively limits the scope of anything in the namespace to the file level (so you can't call the
functions in that namespace from another other file). This is comparable to the effect of the static
keyword.
Renaming namespaces
Finally, if you just don't feel like typing the entire name of namespace, but you're trying to
keep to a good style and not use the using keyword, you can rename a namespace to reduce the
typing:
namespace <new> = <old>
10. (i) List the advantages of exception handling mechanisms. (4)
The following are some of the advantages of exception handling mechanisms
1. Diving by zero error handling: the library designer and library user
2. Unconditional termination and program preferred termination.
3. Separating error reporting and error handling.
4. The object destroy problem.
(ii) Write a C++ program for the following : (12)
(1) A function to read two double type numbers from keyboard.
(2) A function to calculate the division of these two numbers.
(3) A try block to throw an exception when a wrong type of data is keyed in.
(4) A try block to detect and throw an exception if the condition''divide-by-zero''
occurs.
(5) Appropriate catch block to handle the exceptions thrown.
25
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
11. Write brief notes on Standard template Library (16)
The collection of generic classes and functions is called the Standard Template
Library (STL). STL components which are now part of the standard C++ library are defined in
the namespace std. We must therefore use the using namespace directive
using namespace std;
26
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
Components of STL
Containers
Types of container are;
sequence container
· Vector - it allows insertion and deletion at back – it permits direct access- header file is < vector >
· Deque - double ended queue – it allows insertion and deletion at both ends- permits direct
accessheader
file is < deque>
· List - allows insertion and deletion anywhere – header file is < list >
Associative container
· Set - used for storing unique set – it allows rapid look up- bidirectional access - header file is < set >
· Multiset - Used for storing non unique set – header file is < set >
· Map - Used for storing unique key/value – header file is <map>
· Multimap
Derived container
· Stack - Last in first out – no iterator- header file is < stack >
· Queue - First in first out – no iterator- header file is < queue>
· priority queue - first element out is always with the highest priority- header file is <queue>- no
iterator
 Algorithms
 Iterators
 Application of Container Classes
12. Write a program which copies the contents of one file to a new file by removing
unnecessary spaces between words.
27
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
28
CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE
Download