Object Oriented Programming
Object Oriented Programming
Aim: To understand the concepts of object-oriented programming and master OOP using C++.
UNIT I
9
Object oriented programming concepts – objects – classes – methods and messages – abstraction and encapsulation
– inheritance – abstract classes – polymorphism.
Introduction to C++ – classes – access specifiers – function and data members – default arguments – function
overloading – friend functions – const and volatile functions - static members – Objects – pointers and objects –
constant objects – nested classes – local classes
UNIT II
9
Constructors – default constructor – Parameterized constructors – Constructor with dynamic allocation – copy
constructor – destructors – operator overloading – overloading through friend functions – overloading the
assignment operator – type conversion – explicit constructor
UNIT III 9
Function and class templates - Exception handling – try-catch-throw paradigm – exception specification – terminate
and unexpected functions – Uncaught exception.
UNIT IV 9
Inheritance – public, private, and protected derivations – multiple inheritance - virtual base class – abstract class –
composite objects Runtime polymorphism – virtual functions – pure virtual functions – RTTI – typeid – dynamic
casting – RTTI and templates – cross casting – down casting .
UNIT V 9
Streams and formatted I/O – I/O manipulators - file handling – random access – object serialization – namespaces -
std namespace – ANSI String Objects – standard template library.
Total: 45
TEXT BOOKS:
REFERENCES:
Ira Pohl, “Object Oriented Programming using C++”, Pearson Education, Second Edition Reprint 2004..
S. B. Lippman, Josee Lajoie, Barbara E. Moo, “C++ Primer”, Fourth Edition, Pearson Education, 2005.
B. Stroustrup, “The C++ Programming language”, Third edition, Pearson Education, 2004.
struct Y {
// public by default
int f() { return a = 5; };
private:
// private data member
int a;
};
EXTRA QUESTIONS
1.Give the evolution diagram of OOPS concept.
Machine language
Procedure language
Assembly language
OOPS
2.What is Procedure oriented language?
Conventional programming, using high-level language such as COBOL, FORTRAN and C are commonly known as
Procedure oriented language (POP). In POP number of functions are written to accomplish the tasks such as reading,
calculating and printing.
3) Give some characteristics of procedure-oriented language.
• Emphasis is on doing things (algorithms).
• Larger programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Employs top-down approach in program design.
Function-1 Function-2 Function-3
Function-4 Function-5
Function-6 Function-7 Function-8
Main program
4) Write any four features of OOPS.
• Emphasis is on data rather than on procedure.
• Programs are divided into objects.
• Data is hidden and cannot be accessed by external functions.
• Follows bottom -up approach in program design.
5) What are the basic concepts of OOPS?
• Objects.
• Classes.
• Data abstraction and Encapsulation.
• Inheritance.
• Polymorphism.
• Dynamic binding.
• Message passing.
6) What are objects?
Objects are basic run-time entities in an object-oriented system. They may represent a person, a place, a bank
account, a table of data or any item that the program has to handle. Each object has the data and code to manipulate
the data and theses objects interact with each other.
7)What is a class?
• The entire set of data and code of an object can be made a user-defined data type with the help of a class.
• Once a class has been defined, we can create any number of objects belonging to the classes.
• Classes are user-defined data types and behave like built-in types of the programming language.
class B
{
private:
int b;
public:
B() { b = 6; }
friend void ::show(A& x, B& y); // declaration of global friend
friend void A::show(A& x, B& y); // declaration of friend from other class
};
show(a,b);
a.show(a,b);
}
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of
classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be executed depending
on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
return 0;
}
#include<iostream.h>
#include<conio.h>
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
void swap(float &p,float &q)
{
float t;
t=p;
p=q;
q=t;
}
void swap(char &c1,char &c2)
{
char t;
5. Explain the special features of object oriented programming. (16) (NOV/DEC 2010)
Objects : Objects are the basic run time entities in an object oriented system. They are instance of
a class. They may represent a person, a place etc that a program has to handle. They may also
represent user-defined data. They contain both data and code.
Classes : Class is a collection of objects of similar data types. Class is a user-defined data type.
The entire set of data and code of an object can be made a user defined type through a class.
Data Abstraction : Abstraction refers to the act of representing the essential features without
including the background details or explanations.
Encapsulation The wrapping up of data and functions into a single unit is known as data
encapsulation. Here the data is not accessible to the outside world. The insulation of data from
direct access by the program is called data hiding or information hiding.
Inheritance : Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification and provides the
idea of reusability. The class which is inherited is known as the base or super class and class
which is newly derived is known as the derived or sub class.
Message Passing : Objects communicate between each other by sending and receiving information
known as messages. A message to an object is a request for execution of a procedure. Message
passing involves specifying the name of the object, the name of the function and the information
to be sent.
The friend function is written as any other normal function, except the function declaration of these functions is
preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed
to it in argument.
7. (i) Write a C++ program to multiply two matrices and print the result.
#include<iostream.h>
Class matrix
{
Private: int a[3][3];
Public: void getmatrix(int r, int c);
void printmatrix(int r, int c);
void mul(matrix,matrix);
};
Void matrix::getmatrix(int r, int c)
{
int I,j;
cout<<”Enter matrix elements”;
For( i=0;i<r;i++)
For(j=0;j<c;j++)
Cin>>a[i][j];
}
Void matrix::printmatrix(int r, int c)
{
Int I,j;
For(i=0;i<r;i++)
Void main()
{
Matrix A[3][3],B[3][3],C[3][3];
Int r1,r2,c1,c2;
Cout<<”enter order of 2 matrices”;
Cin>>r1>>c1>>r2>>c2;
Try
{
If(r2==c1)
{
A.readmatrix(r1,c1);
B.readmatrix(r2,c2);
C=mul(A,B);
A.printmatrix(r1,c1);
B.printmatrix(r2,c2);
C.printmatrix(r1,c2);
Exit(0);
}
else
{ throw (c2);
}
}
Catch(int x)
{
Cout<<”Invalid matrix order”;
}
(ii) Explain inline functions with an Example program(APR/MAY 2010) An inline function is
a function that is expanded in line when it is invoked. The compiler
Replaces the function call with corresponding function code. The inline funcitions are defined
As follows:
inline function-header
{
Function body;
}
Example:
inline double cube(double a)
{
Return(a*a*a);
}
Some situations where inline expansion may not work are:
For functions returning values, if a loop , a switch, or a goto exists.
For functions not returning values, if a return statement exists.
If functions contain static variables.
If inline functions are recursive.
-Example program to illustrate inline functions :
#include <iostream.h>
inline float mul(float x, float y)
{ return(x*y); }
inline double div(double p, double q)
{ return(p/q) ; }
int main( )
{
float a=1.2 ;
float b=2.3;
cout<< mul(a,b)<<”\n”;
cout<< div(a,b)<<”\n”;
return 0;
}
8.(i) Explain the concept of pointers with an example program written inC++.
#include <iostream>
using namespace std;
This passes references to three arrays, each holding 1,000 ints and defined by the typedef vector. It loops through
all elements, adding each of the elements and storing the result in the third.
(ii) How is function overloading different from operator overloading. (APR/MAY 2010)
Function Overloading:
A single function name can be used to perform different types of tasks. The same function name can be used to
handle different number and different types of arguments. This is known as function overloading or function
polymorphism.
#include<iostream.h>
#include<conio.h>
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
void swap(float &p,float &q)
{
float t;
t=p;
p=q;
q=t;
}
void swap(char &c1,char &c2)
{
char t;
t=c1;
c1=c2;
c2=t;
}
void main()
{
int i,j;
float a,b;
char s1,s2;
clrscr();
cout<<"\n Enter two integers : \n";
cout<<" i = ";
cin>>i;
operator overloading:
The process of making an operator to exhibit different behaviors at different instances.
• Only existing operators can be overloaded.
• We cannot change the basic meaning of an operator.
• The overloaded operator must have at least one operand.
• Overloaded operators follow the syntax rules of the original operators.
-General form of operator function is:
Return type classname :: operator (op-arglist)
{
Function body
}
Overloaded operator functions can be invoked by expression
x op y for binary operators
In the following program overloaded function is invoked when the expression c1+c2 is encountered. This
expression is the same as operator op(x,y) (ie) operator +(c1,c2)
UNIT II
9
Constructors – default constructor – Parameterized constructors – Constructor with dynamic allocation – copy
constructor – destructors – operator overloading – overloading through friend functions – overloading the
assignment operator – type conversion – explicit constructor
1) It tells the return type of the data that the function will return.
2) It tells the number of arguments passed to the function.
3) It tells the data types of the each of the passed arguments.
4) Also it tells the order in which the arguments are passed to the function.
Therefore essentially, function prototype specifies the input/output interlace to the function i.e. what to give to the
function and what to expect from the function.
3. Explain the multiple meanings of the operators « and » in C++ and their precedence. (Nov/dec 2011)
8. What is the need for overloading the assignment operator? .(APR/MAY 2011)
The assignment operator is used to copy the values from one object to another already existing
object. The key words here are “already existing”. Consider the following example:
Cents cMark(5); // calls Cents constructor
1
Cents cNancy; // calls Cents default constructor
2
cNancy = cMark; // calls Cents assignment
3
operator
In this case, cNancy has already been created by the time the assignment is executed. Consequently, the
Cents assignment operator is called. The assignment operator must be overloaded as a member function.
10. List any four operators that cannot be overloaded. (NOV/DEC 2010)
• Class member access operator (. , .*)
• Scope resolution operator (::)
• Size operator ( sizeof )
• Conditional operator (?:)
11. Write the difference between realloc() and free().(APR/MAY 2010)
An existing block of memory which was allocated by malloc() subroutine, will be freed by free()
subroutine. In case , an invalid pointer parameter is passed, unexpected results will occur. If the parameter is a null
pointer, then no action will occur.
Where as the realloc() subroutine allows the developer to change the block size of the memory which was pointed to
by the pointer parameter, to a specified bytes size through size parameter and a new pointer to the block is returned.
12. Give the purpose of gets and puts function. (APR/MAY 2010)
gets()
char * gets ( char * str );
Get string from stdin
Reads characters from stdin and stores them as a string into str until a newline character ('\n') or the End-of-
File is reached.
puts()
int puts ( const char * str );
Write string to stdout
Writes the C string pointed by str to stdout and appends a newline character ('\n').
EXTRA QUESTIONS:
1. Define constructor?
A function with the same name as the class itself responsible for construction and returning objects of the
class is called constructor.
2. What do you mean by copy constructor?
Copy constructor is used to copy the value of one object into another. When one object is copied to another
using initialization , they are copied by executing the copy constructor.
The copy constructor contains the object as one of the passing argument.
3. Define default constructor and give example?
A constructor without any argument is called default constructor.
Ex Class complex
{ Public: void complex(); };
4. What is parameterized constructor?
A constructor with one or more than one argument is called parameterized constructor.
Ex
Class complex
{ Public: Complex complex( int real, int imag); };
5. Define destructor?
The function which bears the same name as class itself preceded by ~ is destructor. The destructors
automatically called when the object goes out of scope.
6. What do you mean by explicit constructor?
The one argument constructor which is defined with keyword explicit before the definition. Explicit word
prohibits the generation of conversion operator for a single argument constructor.
7. Explain multiple constructor?
A class with more than one constructor comes under multiple constructor. Multiple constructor is
constructed with different argument list. That is either with empty default constructor or with parameterized
constructor.
8. What is operator overloading?
The process of giving an existing operator a new , additional meaning is called operator overloading.
9. What is the lifetime of an object?
The life time of a global object is throughout the execution of the program. Otherwise , the object comes
into existence when constructor is over and is alive till it gives out of scope, i.e just before the destructor is
applied.
10. List out the operator which can not be overloaded ?
1. The dot operator for member access.(.)
2. The dereference member to class operator .( *)
3. Scope resolution operator.
4. Size of operator (sizeof).
1. Write a program to overload the stream insertion and stream extraction operators to handle data of
a user-defined telephone number class called Phone Number. (Nov/dec 2011)
Overloaded stream insertion and stream extraction operators for class PhoneNumber
// PhoneNumber.cpp
2 // Overloaded stream insertion and stream extraction operators
3 // for class PhoneNumber.
4 #include <iomanip>
5 using std::setw;
6
7 #include "PhoneNumber.h"
8
#include<iostream.h>
#include<conio.h>
class complex
{
private:
float real;
float img;
public:
complex()
{
real=0.0;
img=0.0;
}
complex(float a,float b)
{
real=a;
img=b;
}
friend complex operator +(complex,complex);
void display()
{
cout<<"\n"<<real<<"+-i"<<img<<"\n";
}
};
complex operator +(complex c1,complex c2)
(ii) Explain type conversion with suitable example (8) (Nov/dec 2011)
There are three types of conversions. They are
• Conversion from basic type to class type – done using constructor
• Conversion from class type to basic type – done using a casting operator
• Conversion from one class type to another – done using constructor or casting operator
4. Write
1. Explain copy constructor with an example.(8)
struct A {
int i;
A() : i(10) { }
};
struct B {
int j;
B() : j(20) {
cout << "Constructor B(), j = " << j << endl;
}
struct C {
C() { }
C(C&) { }
};
int main() {
A a;
A a1(a);
B b;
const B b_const;
B b1(b);
B b2(b_const);
const C c_const;
// C c1(c_const);
}
The following is the output of the above example:
Constructor B(), j = 20
Constructor B(), j = 20
Copy constructor B(B&), j = 20
Copy constructor B(const B&, int), j = 30
class Y {
private:
char * string;
int number;
public:
// Constructor
Y(const char*, int);
// Destructor
int main () {
// Create and initialize
// object of class Y
Y yobj = Y("somestring", 10);
// ...
6. Explain the different types of constructors with suitable examples. (16) (NOV/DEC
2010)
class code
{
int id;
public:
code(){} // default constructor
code(int a) { id = a;} // parameterized constructor
code(code & x) // copy constructor
{
id = x.id;
}
void display(void)
{
cout << id;
}
};
int main()
{
code A(100);
code B(A);
code C =A;
code D;
D = A;
cout << “\n id of A: “ ; A.display();
cout << “\n id of B: “ ; B.display();
cout << “\n id of C: “ ; C.display();
cout << “\n id of D: “ ; D.display();
return 0;
}
private:
int m_i;
};
int main()
{
Point sPoint;
sPoint.PrintPrivate();
ChangePrivate(sPoint);
sPoint.PrintPrivate();
}
Output
0
1
8. What happens when a raised exception is not caught by catch block? (APR/MAY 2010)
When a raised exception not caught by catch block , if the match is not found, the catch block calls a built in
function terminate(), which terminate the program execution by calling a built in function abort().
9. Give the syntax of a pointer to a function which returns an integer and takes arguments one of
integer type and 2 of float type. (APR/MAY 2010)
#include<iostream.h>
Void main()
{
int pointaccess( int d1, float f1);
int a =10;
float x = 2.5;
cout << pointaccess(d1, f1);
int (*pointfun)(int,float);
pointfun = pointaccess;
cout << (*pointfun) (a,x);
}
int pointaccess(int aa, float ff)
{
Cout << aa << ff ;
Return( aa + ff );
}
EXTRA QUESTIONS:
1. What is function template?
Function templates are generic functions, which work for any data type that is passed to them. The data
type is not specified while writing the function. while using that function, we pass the data type and get the
required functionality.
7. What is instantiation?
Generation of either function or class for a specific type using the class of function template is known as
instantiation of the class or function.
void main()
{
int a[10];
float b[10];
char c[10];
cout<<"\n Enter 5 integers:";
for(int i=0;i<size;i++)
cin>>a[i];
print(a, size);
cout<<"\n Enter 5 float values:";
for(i=0;i<size;i++)
cin>>b[i];
print(b, size);
cout<<"\n enter 5 characters:";
for(i=0;i<size;i++)
cin>>c[i];
print(c,size);
}
void main()
{
int a[10];
float b[10];
char c[10];
cout<<"\n Enter 5 integers:";
for(int i=0;i<size;i++)
cin>>a[i];
print(a, size);
cout<<"\n Enter 5 float values:";
for(i=0;i<size;i++)
cin>>b[i];
print(b, size);
cout<<"\n enter 5 characters:";
for(i=0;i<size;i++)
cin>>c[i];
print(c,size);
}
5. (i) Explain with an example. How exception handling is carried out in C++. (8)
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.
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 appropitely.
Exception object
Catch block
General form
try
{
…..
throw exception;
…….
}
Catch ( type arg)
{
……
}
Exceptions that has to be caught when functions are used- The form is as follows:
try
{
…..
throw exception;
…….
}
Catch ( type arg)
{
……// catch block1
}
Catch ( . . .)
{
……
}
(ii)Write a class template to insert an element into a linked list.(8) .(APR/MAY 2011)
Program:
#include<iostream.h>
#include<conio.h>
#include<process.h>
template<class T>
class list
{
private:
int data;
list *next;
public:
list()
void main()
{
clrscr();
int choice,data;
list<int> *first=NULL;
list<int> *node;
while(1)
{
cout<<"\n 1.insert\n";
cout<<"\n 2.display\n";
cout<<"\n 3.quit\n";
cout<<"\n choice[1-3]:\n";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\n Enter data:";
cin>>data;
node=new list<int>(data);
if(first==NULL)
first=node;
else
stack::stack()
{
top=0;
for(int i=0;i<size;i++)
a[i]=0;
}
int stack::isempty()
{
return(top==0?1:0);
}
int stack::isfull()
{
return(top==size?1:0);
}
void stack::push(int i)
{
try
{
if(isfull())
{
throw"full";
}
else
void main()
{
int a[10];
float b[10];
cout<<"\n Enter 5 integers:";
read(a, 5);
cout << minimum(a,5);
cout<<"\n Enter 5 float values:";
read(b,5);
cout << minimum(b,5);
}
#include<iostream.h>
Void main()
{
9. Write a C++ program to create a base class called house. There are two classes called
door and window available. The house class has members which provide information related to
the area of construction, doors and windows details. It delegates responsibility of computing the cost
of doors and window construction to door and window classes respectively. Write a C++ program to
model the above relationship and find the cost of constructing the house. (APR/MAY 2010)
Class door
{
public:
10. 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. (APR/MAY 2010)
#include<iostream.h>
Void Mysqrt()
{
cout << “ inside the function mysqrt”
try
{
if(x < 0)
throw x;
else
Cout << “ square root of x = << sqrt(x);
}
void main()
{
int x;
cin >> x;
Mysqrt();
catch( int z)
{
cout << “ caught an exception , the input value is negative”
}
}
UNIT IV 9
Inheritance – public, private, and protected derivations – multiple inheritance - virtual base class – abstract class –
composite objects Runtime polymorphism – virtual functions – pure virtual functions – RTTI – typeid – dynamic
casting – RTTI and templates – cross casting – down casting .
Multiple Inheritance
• A class derived from more than one Base class
Multilevel Inheritance
• Deriving a class from another Derived class.
Hybrid Inheritance
• A class may be inherited from more than one Derived class
- When a base class is privately inherited by a derived class, Public members of the base class become private
members of derived class.
- the public members of base class can only be accessed by the member functions of the derived class.
- They are inaccessible to the objects of the derived class
Public Derivation
Class ABC : public XYZ
{
members of ABC
};
- When a base class is publicly inherited by a derived class, Public members of the base class become public
members of derived class.
- They are accessible to the objects of the derived class.
- The private members of base class will never become the members of its derived class.
Example
class B
{
int a;
public:
int b;
void get_ab();
int get_a(void);
void show_a(void);
};
class D : public B // public derivation
{
int c;
public:
void mul(void)
void display(void);
};
Multilevel Inheritance
• Deriving a class from another Derived class.
Output:
Roll number=111
Marks in sub1=85
Marks in sub2=70
Total=155
Multiple Inheritance
• A class derived from more than one Base class
Class N
{
Protected:
Output:
M=10
N=20
M*n=200
Output:
B
A
B
2. Demonstrate runtime polymorphism with an example. (Nov/dec 2011)
The two types of polymorphism are,
• Compile time polymorphism – The compiler selects the appropriate function for a particular call at the compile
time itself. It can be achieved by function overloading and operator overloading.
• Run time Polymorphism - The compiler selects the appropriate function for a particular call at the run time only. It
can be achieved using virtual functions
Program to implement runtime polymorphism:
include<iostream.h>
#include<conio.h>
3. Illustrate virtual function and pure virtual function with suitable example? (Nov/dec 2011)
Virtual Function:
#include<iostream.h>
#include<conio.h>
class abc
{
protected :
int a,b;
public:
void take()
{
cout<<"\nEnter two 'int' values::";
cin>>a>>b;
}
virtual void display()=0;
};
class xyz:public abc
{
public:
void display()
{
cout<<"\nSum for 1st derived class="<
}
};
class mn:public abc
{
public:
void display()
{
void main()
{
base *b; derived1 d1; derived2 d2;
Class N
{
Protected:
Int n;
Public:
Void get_n(int);
};
Class P: public M, public N
{
Public:
Void display(void);
};
Void M:: get_m(int x)
{
M=x;
}
Output:
M=10
N=20
M*n=200
#include <iostream>
#include <typeinfo> // Header for typeid operator
using namespace std;
// Base class
class MyBase {
public:
virtual void Print() {
cout << "Base class" << endl;
};
};
// Derived class
class MyDerived : public MyBase {
public:
void Print() {
cout << "Derived class" << endl;
};
};
int main()
{
// Using typeid on built-in types types for RTTI
cout << typeid(100).name() << endl;
cout << typeid(100.1).name() << endl;
MyBase* ptr1;
ptr1 = d1;
if ( typeid(*ptr1) == typeid(MyDerived) ) {
cout << "Ptr has MyDerived object" << endl;
}
OUTPUT:
i
d
6MyBase
9MyDerived
9MyDerived
Ptr has MyDerived object
Ptr has MyDerived object
5.
a. Give the rules for writing virtual functions. (6)
1.The virtual function must be member of class
2. They cannot be static members
3. They are accessed by using object pointers
4. Prototype of base class function & derived class must be same
5. Virtual function in base class must be defined even though it is not used
6. A virtual function can be friend function of another class
7. We could not have virtual constructor
8. If a virtual function is derived in base class, it need not be necessarily redefined in the derived class
9. Pointer object of base class can point to any object of derived class but reverse is not true
10. When a base pointer points to derived class, incrementing & decrementing it will not make it point to the
next object of derived class
Write a C++ program to illustrate the use of virtual function. (10) (NOV/DEC 2010)
#include<iostream.h>
#include<conio.h>
class abc
{
protected :
int a,b;
public:
void take()
{
cout<<"\nEnter two 'int' values::";
cin>>a>>b;
}
virtual void display()=0;
};
class xyz:public abc
{
public:
void display()
{
cout<<"\nSum for 1st derived class="<
}
6. What are abstract classes? Write a program having student as an abstract class and create
many derived classes such as engineering, science, medical etc., from the student class. Create
their object and process them. (APR/MAY 2010)
A class with no object is called abstract class.
#include<iostream.h>
class student
{
Public:
Int regno;
char name[20];
};
class engineering:public student
{
char branch[20];
public:
void get()
{
cin>>regno>>name>>branch;
}
void put()
{
cout<<regno<<name<<branch;
};
class science:public student
{
char branch[20];
4. What is the member function used in manipulating string objects? (Nov/dec 2011)
The member function used in manipulating string objects are
insert()-inserts character at specified location
erase()- removes characters as specified
replace()-replace specified characters with a given string
append()- appends a part of string to another string
5. Justify the need for object serialization. (APR/MAY 2011)
Serialization is simple, it is basically converting a class into binary form so that it can be read later on or
sent over a network and then read out of the file or over the network as an object. It is a simple yet
powerful concept, and allows an object to retain its form even across a network.
6. Name the features included in C++ for formatting the output. (NOV/DEC 2010)
1. Field Width
2. Justification in Field
3. Controlling Precision
4. Leading zeros
7. What is file mode? List any four file modes. (NOV/DEC 2010)
8. Give the meaning of the flag ios::out. (APR/MAY 2010)
ios::out-open the file for writing.
9. What is a C++ manipulator? (APR/MAY 2010)
Manipulators are the functions to manipulate the output formats.
EXTRA QUESTIONS:
1. What are streams?
A stream is a conceptual pipe like structure, which can have one end attached to the program and other end
attached by default to a keyboard, screen or a file. It is possible to change where one end is pointing to,
while keeping the other end as it is.
2. List all formatted I/O in C++?
The following list of ios functions are called formatted I/O in C++
Width(), precision(), fill(), setf(), unsetf().
3. Define manipulator?
Manipulator are funtions which are non member but provide similar formatting mechanism as ios functions
4. Write the difference between manipulators and ios function?
The major difference in the way the manipulators are implemented as comp[ared to the ios member
functions. The ios member functions return the previous format state which can be used latter if necessary.
But the manipulator does not return the previous state.
5. Explain setf()?
The function specifies format flags that controls output display like left or right justification, padding after
sign symbol, scientific notation display, displaying base of the number like hexadecimal, decimal, octal etc.
Ex cout.setf(ios::internal,ios::adjustfield); Cout.setf(ios::scitific,ios::floatfield);
6. Define Namespace?
Namespace is a kind of enclosure for functions, classes and variables to separate them from other entities.
7. Explain get() and put() function?
The classes istream and ostream define two member functions get() and put() respectively to handle a
single character input and output operations. The function cin.get() had two different versions. The first
version has a prototype void get(char) and the other has prototype char get(void). The fuction cout.put()
used to display a character .
8. Explain read() and write() function?
#include <fstream>
using std::ofstream;
using std::ostream;
using std::fstream;
#include <iomanip>
using std::setw;
using std::setprecision;
#include <cstdlib>
using std::exit; // exit function prototype
int enterChoice();
void createTextFile( fstream& );
void updateRecord( fstream& );
void newRecord( fstream& );
void deleteRecord( fstream& );
int main()
{
// open file for reading and writing
fstream inOutCredit( "credit.dat", ios::in | ios::out );
return 0;
} // end main
int menuChoice;
cin >> menuChoice; // input menu selection from user
return menuChoice;
} // end function enterChoice
// update record
if ( client.getAccountNumber() != 0 )
{
outputLine( cout, client ); // display the record
return accountNumber;
} // end function getAccount
2. Write brief notes on Standard template Library (16) (Nov/dec 2011)
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;
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 access-
header file is < deque>
• List - allows insertion and deletion anywhere – header file is < list >
Associative container
Algorithms
Iterators
Application of Container Classes
3. Illustrate different file operations in C++ with suitable example? (Nov/dec 2011)
The Basic operation on text/binary files are : Reading/writing ,reading and manipulation of data stored on
these files. Both types of files needs to be open and close.
How to open File
Using member function Open( ) Using Constructor
Syntax Syntax
Filestream object; Filestream object(“filename”,mode);
Object.open(“filename”,mode);
Example Example
ifstream fin;
fin.open(“abc.txt”) ifstream fin(“abc.txt”);
Syntax
fileobject.close( );
Example
Program
include<fstream>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
char str[80];
fin.open("abc.txt");
fin>>str; // read only first //string from file
cout<<"\n From File :"<<str; // as //spaces is treated
as termination point
getch();
return 0;
}
NOTE : To overcome this problem use
fin.getline(str,79);
Syntax Example
Filestream_object.eof( ); // detecting end of file
Example #include<iostream>
#include<iostream> #include<fstream>
#include<fstream> #include<conio.h>
#include<conio.h> using namespace std;
using namespace std; int main()
int main() {
{ char ch;
char ch; ifstream fin;
ifstream fin; fin.open("abc.txt");
fin.open("abc.txt"); while(fin) // file object
while(!fin.eof()) // using eof() function {
{ fin.get(ch);
Example : To read the contents of a text file and display them on the screen.
Program ( using getline member function) Program ( using get( ) member function)
#include<fstream> #include<fstream>
#include<conio.h> #include<conio.h>
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
char str[100]; char ch;
ifstream fin; ifstream fin;
fin.open("c:\\abc.txt"); fin.open("file6.cpp");
while(!fin.eof()) while(!fin.eof())
{ {
fin.getline(str,99); fin.get(ch);
cout<<str; cout<<ch;
} }
fin.close(); fin.close();
getch(); getch();
return 0; return 0;
} }
4.
a. List the different stream classes supported in C++
b. Write a C++ program to read the contents of a text file .(APR/MAY 2011)
5.
a. Explain the use of any six manipulators with example. (6)
Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction
(>>) operators on stream objects, for example:
cout << boolalpha;
They are still regular functions and can also be called as any other function using a stream object as argument, for
example:
boolalpha (cout);
Manipulators are used to change formatting parameters on streams and to insert or extract certain
special characters.
nput manipulators
ws-Extract whitespaces (manipulator function)
Output manipulators
endl-Insert newline and flush (manipulator function)
ends-Insert null character (manipulator function)
flush-Flush stream buffer (manipulator function)
Parameterized manipulators
These functions take parameters when used as manipulators. They require the explicit inclusion of the header file
<iomanip>.
setiosflags-Set format flags (manipulator function)
resetiosflags-Reset format flags (manipulator function)
setbase-Set basefield flag (manipulator function)
setfill-Set fill character (manipulator function)
setprecision-Set decimal precision (manipulator function)
setw-Set field width (manipulator function)
void main(void)
{
char buffer[SIZE];
Output:
6. Write a program which copies the contents of one file to a new file by removing
unnecessary spaces between words. (APR/MAY 2010)
#include<iostream.h>
#include<fstream.h>
main()
{
ofstream outfile;
ifstream infile;
infile.open(“sample”);
outfile.open(“sample1”);
while(outfile.feof()!=0)
{
char c=outfile.get();
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. This classes are called String Classes. These classes are declared in the header file
iostream.This file should be included in all the programs that communicate with the console unit.
ios is the base class for istream(input stream)and ostream(output stream) which are ,in turn, base classes for
iostream(input/output stream).The class ios is declared as the virtual base class so that only one copy of its members
are inherited by the iostream.
The class ios provides the basic support for formatted and unformatted I/O operations. The class istream
provides the facilities for formatted and unformatted input while the class ostream provides the facilities for
formatted and unformatted output. The class iostream provides the facility for handling both input and output
streams. Three classes,namely,istream_withassign,ostream_withassign and iostream_withassign add assignment
operators these classes.
ios (General input/output stream class)
1. Contains basic facilities that are used by all other input and output classes.
2. Also contains a pointer to a buffer object(streambuf object).
3. Declares constants and functions that are necessary for handling formatted input and output operation.
istream(input stream)
1. Inherits the properties of ios
2. Declares input functions such as get(),getline() and read().
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;
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>