Q.2 Explain the need of object or
[unie 1 | ne
Chepter- 6 Standard Template Library (67) To TBO}
troduction to STL. 6-1
6.2 STL Components... 6-1
6.3 Sequence Container 6-2
6.4 Associative Container. 6-4
6.5 Container Adapter. 6-6
8.6 AlgOrItAME rasan 6-11
6.7 Set Operations ecu ‘ 8-15
6.8 Heap Sort . 6-16
6.9 Iterators - input, Output, Forward, Bidirection
and Random Access nen = 18
6.10 Object Oriented Programming - A Road Map to Future ..6 -20
Solved Model Question Paper (M- 1) to (M2)
Solved SPPU Question Paper (S-1toS-6)
)
|. Emphasis son data rather than
Fundamentals of
Object Oriented Programming
1.1 : Introduction to Procedural, Modular, Generic
and Object Oriented Programming Techniques
6, Some common properties a
1.3 + Funds
2.3 Explain the features of ob
(ea (SPU bay 37
.1 Compare procedure ot
Programming.
Ans. :
obje
8 (SPPU : Dec.-i9, Nay.
Se. No.
‘Object Oriented
Programming Language
(op)
Procedural Programming
| Ana: 4. Object
Language
+ Object is am instance of a «
+ Opler are baste suri,
~ + Tm Ges the class variables
‘sess membervariah
+ Example
rae ft:
Forte las Frat the object
Ths major foeas i on procedures The sain Tous ls on objec asses : USIEISSTERRE
5 functions. 2c The
(2) Pe ety st joie. Dane aang p mcatae | EE
important feature of OOF. ara
ie
2, This is a top down programming Tis
approach,
bottom up
Programming approach,
Data biding can be done by
private:
int len, Be,
simple to implement. 11 is complex to implement
| For example : C, Foran, For example = C++, JAVA
coBoL,
cod
PE a eh tae |1.2 : Need of Object Oriented Programming
22 Explain the need of ot 4 peosramming
Fundamentals of
Object Oriented Programming
‘duction to Procedural, Modular, Generic
Sct Oriented Programming Techniques
fedure erlented programming ve, object
em (SPP bes
‘ral Programming bj
riebted
Language
Programming Language
(oP)
——___ f00P)"
lua programing
‘des of procedures
Drosranmlng aproech,
ean ison proceakzes
pe
1 isnot posi, abit is one of the
importa: fears 0f OOP,
pon
[et possible. "Daca Sling san be done by
tmakiog petra.
implement
“A Glee Engewing Ses
ot
sQhim js a abise
{SPIEL iH One Gr
ex fer‘Sauer
raw)
resize
Fig. @.3.2 Hierarchical structure of inheritance
a What ig the difference between data encapeu
abstraction ?
Ans,
So) Data excaprulaion
No. :
1. This a process of binding data
members of a class to the member
fnetions ofthat class.
Data abstraction
2 = Data encapsulation depends upon
“g, object data type.
It is used in software
implementation phase
Data encapsulation can be
achieved by inheritance,
————
“A Guide for Engineering Stes
jet OentedProgramming_2°5 ect Orit Prepon
ject rented Programming _1-5_Ott Orient
14 : Benefits of OOP
2.5 What are the benefits of OOP ? :
joing ae some advantages of object oriented
ce the redundant code can be cl
can be used
og modules can be crested using
ye modules can then communicat
\2eDue to data hiding propery, important data can be kept aay &
smauthorized access
4. Its possible to creste multiple objects for a given class.
5. For upgrading the system ffom small scale to large scale is poss
due to object oriented fearure.
6. Due to data centered nature of object oriented programming mos
the deuals of the application model can be captured
7. Message passing technique in object oriented programming allows be
objects to communicate to the external systems.
8 ng the code for simplicity, understanding and debuseios
ible due to
Q8 What is the difference between C and C++?
Ans.
C language
C isa procedure oxented
language
2 | C makes
approach of
Soest 1 Guiee for Engincerng Ste{int main)
q
ented programming -
+ eliminated and the
cout <"Hello World\n'
>
using object oriented
fate t0 each other to
‘28 What are primitive data types and user
1 be kept away from
lass.
ge scale is possible
tentals of
gramming Object Ortente Programming 1-7
1.6 : C++ Programming Basics
deunming most of | 0.7 Give the structure of Cre
a Ans.: There are
four sections in the structure of C++ progtam - |
|
tCet Oriented Programming
o
Ans. : Definition : Aapieet
Fundamentels of
beet Oriented Program,
oie aures with sultable example
ucture. Thus: sty i cllection of Various dsta item:
‘The Syntax of declaring steucture in Cry is as follows
struct name {
member 1;
member 2;
member n;
h
Example :
struct stud {
{int roll_no; | The stud 1 and stud 2 will look like this
char name[10j; | [~~
float marks;
b
struct stud stud1,stud2;
Q.10 Write a C program to represent a complex number using
structure and add"two complex numbers.
Ans.
#include
using namespace std;
typedef strict Complex
{
float real;
float img;
Fat
Object Orented Programming 179 Object Orient
ject Oriente
vvold main)
: a
om enum ne
couch art of Sst complex number. For exat
eee
aces ‘
pee ee ee
ee reac
out Oatput
‘The string : Holo
‘The copied string i: Hebe
| the now string is: Friends
veld mating) ‘The concatenated string ie
HolloFriends
Pinctude
‘using sameepace std
1.13 : Class and Object -
48 Define the term class. a [SPPU May-26, Marks 2}
Ans, : * Each classiis/a/collection of data and functions’ that manipulate
the data,
¢ Placing the data and functions together into a single entity is the
central idea in object oriented programming
The nouns in the system specification help the C++ pro
determine the set of classes. The objects for these clas
These objects work together to implement the system,
‘* Classes in C++ is the natural evolution of C notion of struct.
aeons 14 Guide for Engineering Saudensbeet Oriented Programming 1-18 Fundamentals of
Object Oriented Programming
For exam
Object Oriented Programming 1-19
| class rectangle
i t
private:
Int leabr,
Public
vold get_datag);
vold aread)
wold print_datag;
k
Q.49 Give the difference between structure and class
Ans. = i
ee ee IEE
Sr. Structure es ‘Class. |
No.
| By default the members of structure | BY default the members of clase ate
| are public. private,
2, The structure cam not be inherited. ‘The class can be inberited,
i 7 3. The structures do mot require The’ classes require constructors
constructors, for intialiaing the objects.
4, A structure contains omly data Alas cautains the data as well as|
members. she fu
LaZ6 What is class and object ? Differentiate between class and
\ object. : 1 [SPPU # Dee-37, Mars 6)
Ans, : Class : Refer Q18,
Object :
object interacts with the help of
Procedures or the methods defined within the class. |
aes “Goer Engnerng Sede
Furdament
Object Ortented Progra
Difference between Class and Object
[Sr No. Class y Object
Narmada can be the objects of belonging class
the class River.
pe of the class is | The object can be
Throughout the program. destroyed a5
requizements,
‘The class can not be initialized
with some property values
Various" objec taviog
names cen be created fo
same class
1.14 : Class and Data Abstraction
Q.21 How does class play an important role in data abstraction ?
Explain
jbstraction is one of the characteristics of C++ by which
4 representation of the C++ program is presented to the user.
(2) The implementation details are hidden.
(3) Class is used to achieve data abstraction in C+.
(4) Example
class Student
4
Private:
int roll;
char name[10];
public:
void input)
void display();
LN Se
Gees Guide for Engineering StrenFundamentals of
Object Oriented Programming 1-20 Object Oriented Programming
%
In the main function, we can access the functionalities using the object.
For instance -
iden
1.15 : Class Scope and Accessing Class Members
Q22 Explain the method of accessing class members used in
Cé+ with the help of suitable example,
3 class has two types of members - i) Data members and ii)
‘member functions.
(2) Typically the data members are declared as private and member
Aumetions are declared as public. Hence the data members of class are
‘accessed used by member functions of a class.
G) For accessing the class members outside the class, the object of that
class is created and used.
(4) The member functions can be defined inside a class or outside a class.
For defining the member functions outside the class the scope
resolution operator is used,
(S) Example =
#include
using namespace std;
class Test
{
private: Data members aro
pees declared as private.
public:
int Addition(int a, int b)
{
c= ath;
return 6;
the function te data
‘members can be manipulated,
eons A Gulde for Engineering Students
Object Oriented Programming 1-21 Object Ori
)
void Display);
k
void Tost:Display(.)//Using Scope resolution operator
{ //aieplay function is defined outside the clan
cout << "The gum is:" << ¢ << "\n'
)
int main()
4 ea
(Only member functions
are accessinie outsise
se laze because they are
public. |
2.24 Explain the terms private, public and protected,
‘Ans. : © By default the access specifier is of private type
data and functions are declared as private then only members
class can access them. This achieves the data hiding property
Public access specifier allows the function declared outside she
lass to access the data and functions declared under it
‘+ The protected access specifier allows the functions and data declared
under it be accessible by the belonging class and the immediate derived
class. Outside the belonging class and derived class these members art
not accessible.
——
A Guide for Engineering Smdess
Greene
"| = |tunaamentats oy
Object Oriented Programming 1-22 Object Oriented Programming
Object Oriented Programming 1-23 Fandamentels of
Object Ortented Programming
Thus the C++ program cf
© Header files - cont:
definitions and function prototypes
© Source-code files - contains member function definitions
The advantage of this arrangement is that the modification of the
program becomes easy.
1.18 : Functions
Q.26 What is function prototype ?
Ans.: A function prototype is declaration of function without
~ specifying the function body. That is the function prototype specifies
name of function, argument type and retum type.
Q.27 Explain call by value and call by reference with sultable
examples
: 1. Call By Value : In this method, actual values are passed as
parameters to the function. For example
void sum(int x,int y)/*definition*/
{
int ¢:
caxty;
cout<<"\n The Addition is: "<
include
using namespace std;
class TRAIN
{
protected:
cout << "\n Enter trainno: *;
cin >> trainno;
cout << "\n Enter destination: *;
cin >> dost;
cout << “\n Enter distance: ";
cin >> distance; :
+
void show()
{
cout << "\n Train No: " << trainno;
cout << “\n Destination : "<< dest;
cout << "\n Distance :" << distance;
+
void put() _—_// Member function for write file
ee
‘A Guide for Enginesting Students
object Oriented Programming
Fang
1-35 Object Oriented
to file
y
X
int main)
{
TRAIN obj; i
cout << *\aEnter the Record";
1.19 : Accessing Function and Utility Function
2.28 Explain the concept of access and utility function:
Ans. :
+ Access Function
© Itis a fimetion that can read or display data
© Another use of access function is to check the tuth cr fit
jons. Such functions are also called as predicate functions
mnetion
Iper or supporting fiction that can be used by =
to perform some common activities.
© It is a private function because it is not intended to use out
class,
double division(double a, double b)//Utility Function
1
c=a/b;
Tonia jor Ergon
qecones
ide
loObject Oriented Programming 1-26 Object Oriented Prope
‘Goceeecmaaaaunannea terrae geet
(double x, doubley) // Access function
constructors.
4. Tie |/eonstnictor’stotild not have any/return type. Even a void type
should not be written for the constructor.
5, The constructor can not be used as a member of union or structure.
6. The constructors can have default arguments.
\- 632 Write a C++ program for parameterized constructor.
‘Ans, : C+ Program
#include
using namespace std;
class image
4
private
—
Secon A Gulde for Engineering Sudents
IESE ''Z
Object Oriented Programming 1-27 at Grin ei of
ew SS nee rein
int height, width:
public:
Smage(int xt) //oonstructor
4
height=x;
width=¥;
’
int area()
{
retum (height-width);
y
k
int main()
q
image obj1(6,2);
cout<<"The area is :"<
‘using namespace std;
class Arithmetic
{
int d1.d2;
char op;
public:Fundamentals of
Object Oriented Programming 1-28 Object Oriented Programming
Asithmetic(int x.char e.int y)
{
di=x,
dary;
opec;
case /:0=d1/a2;
break;
cout<<"\n Addition of 10+20= "<
using namespace std;
class image
height=new int//assigns memory dynamically using ‘new
image::~image()
«
delete height;//destroys the memory using ‘delete!
delete width;
)
init tmage:sarea()
{
Tetum (*height* *width);
+
int main)
4
image obj1(10,20);
cout<<"The area is :"<
‘using namespace std
void fund)
4
atic int ent=0;
cout << "\ncount =" <
++ Program without using
‘tatle
‘include
tnt ent=0;
‘cout << \ncount = * <
{inline largest(int x,int y,int 2)
flx> y&e8ox>2)
4
cout<-<* First number is greatest and itis: "<<
}
else iffy>sxdeBey>2)
t
‘cout<<" Second number is greatest and itis: "<>x;
cout <<"\n Enter the value of y*;
ein>>y:
/hasing 0b of derived class base class member is accessed
obj.sot_y
obj.show_x0; // access member of B
obj.show_y(); // access member of derived claseObject Oriented Programming 2-3
Inheritance and Pointere
?
output
Enter the value of x90
Enter the value of y70
x= a0
y= 70
In above program the obj is an object of derived class. Using obj we are
‘member function of base class, The derived class inherits
base class using an access specifier public.
G4 Write « C++ program to Inherit base class in private mode.
Ans. :
include
using namespace std
class Base
{
// Yohertt as private
class derived : private Base
¢
int y;
public:
void set_y(int n)
a
7 “Gt for Engncng Sane
ject Oneres Programming 2-4 __A rag
4
yen
>
void show.¥0)
{
cout <<"\n y= "<<¥i
>
%
tnt main()
(
derived obji//object of derived class
nt x :
cout <"\a Enter the value of
oin> > 2. Extensib
cout<<"\n Enter the value of y": oe
As indicated by the comments the above program will generate ens
‘messages “not accessible”. This is because the derived class inherts
base class privately. Hence the public members of base class beat
private to derived class
2.4 : Protected Members
EE Explain why and when do we use protected instead of pit?
Sar SPU tees
= _——___—_—
“A Gul for Engineering Stobjet Oriented Programming
Inheritance and Pointers
but the derived-derived class members are prohibited to
class members.
1, Reusability : The base class code can be used by derived class
need to rewrite the code,
3. Data hiding : Base class can decide to keep some data private so thet
it cannot be altered by the derived class.
4. Overriding : With inheritance, we will be able to override the
methods of the base class so that meaningful implementation of the
base class method can be designed in the derived cless.
2.6 : Constructor and Destructor in Derived Class
@.7 Explain the execution process of constructors and destructors
in derived class.
Ans. : + When we create an object for derived class then fist of all the
Base class constructor is called and after that the Derived class
constructor is called.
SS
‘A Gulde for Engineering Sudents
|
Object Oriented Programming 2-6 Inheritance and Pointers
in function finishes running, the derived class's desrscioe
first and after that the Base class destructor will be
led as chain of constructor calls.
publ
Base()
(cout << "Base constructor” << endl; }
~Baso()
(cout << "Base destructor” << endl; }
hk
class Derived:public Base {
public:
Derived)
{cout << “Derived constructor” << end }
~Derived ()
{cout << “Derived destructor” << endl: }
b
void main()
{
Derived obj;
}
‘The output of above code will be invoking of base class constructer, then
derived class constructor, then derived class destructor and finally base
destructor.
2.7 : Overriding Member Functions
ept with suitable example
Q8 Explain the function overriding conc
‘Ans.: Definition : Redefining a function in a derived class
fun ding.
For example - Consider following C-+ program that wses the sine
fanetion name i.e. print_msg in base class and derived class. The
"a Guide for Engineering SuenObject Oriented Programming 2-7
void got_megd)
{
a=10;
be20,
»
void print_meg()
4
e=a+bi//performing addition
cout<<"\n C(10+20)= "<<;
cout<<"\n Tim print msg() in class A’;
}
8B: public A.
{
private:
int ab
public:
void set_mag()
{
a= 100;
bet0;
= Gaara oeng mea
>
old main)
A obj_base:
‘obj derived.sez_mag ss
obj derived print_msg()//but diferent tasks
we program will display 30 due to execution of print mg
of base class and 90 due to execution of print_msg function o
derived class
PHO] [Teaching
student 3
= 7 ie for Emig SeObject Oriented Programming 2-9
The implementation of class hierarchy
Inheritance.
2.9 : Types of Inheritance
2.10 With suitable examples, explain different typ
Morwrite a note on type - single, mu
‘Ans. : Various types of inhe
2, Multilevel inheritance 3. M\
In single inheritance one child class is
derived fom one base class.
Winelude
‘using namespace sta:
clase Base
public:
void set_x(int 2)
}
void show x)
cout << "nltx =" << x
)
,
class derived : public Base
{
int
pubue:
(obj. show_xy0; // access member of derived class
= ae
Fig. 0.10.2 Mutilevel inheritance
—_——— ee
2, Multilevel inheritance
Bt is a kind of inheritance in which
the derived class is derived. from |
single base class which itself is 0
—
Seco
“A Gude for Engineering StudentsObject Oriented Programming 2-11 Inheritance and Pointers
{cout<< "\n The value of x is "<< x; }
»
class B:public A
void put_b0)
{cout<<"\n The value of y is "<
vold getaim(double &41, double &d2)
4
t= imma;
2 = dima;
}
Virtual double getarea() = 0; // pure virtual function
d
lass square : public area
4
public:
double getarea()
1 Gulde for Engineering Sues
Ohiet Ontnad regmaniag 2:28 hereto
double getarea()
{
double 4, 42:
getdim(at, a2)
retum 0.5 * di * 42;
cour <"\n Calculating area of scruare";
s.setarea(numt uma);
cout << “\nArea of Triangle is: "<< p->getarea():
rotum 0;
»
‘The above program will display area of square as 200 and area of tianale
classes ? Write a program having student
id create many derived. classes’ auch ot
‘te. from the student
‘#include
‘#include
=using namespace std;
class Stuciont
{
char name[10};
public:
oid SeNametcbar nto)
strepy(name.n)
i}
void GetName(char nj10})
{
strepy(n.name);
}
virtual void qualifcation()=0;
class Engg:public Student
{
public:
’ void qualiscation()
{
char
GotName
cout<
{nt maing
{
Student“;
Engg 6;
->qualifcation();
cout<<"\n Enter the name: "<->nm
Output
Enter the name:
Ramesh
Ramesh is a an engineering student
Enter the name:
2.13 : Friend Class
QE Explain the friend class concept.
Similar to a friend function one can declare a class asa friend t0
fanother class. This allows the friend class to access the private data
‘members of the another class.
—_—_————
exes “Ge or Engnerng SaderObject Oriented Programming 2-25
Inheritance and Pointers
For example
clase A
4
onject Oriented Programming
‘Tne program for demons
Siend class B://clase B is friend of class A
public: fincas
Al//eonstructor ose oe =
: { a
dats = 5 heats
% int a; // Note that this member is public
a class inner =
clase B t oe
; public . =
void fun(outer *o,int val)
public: a“ Fo:
{nt subtint 2) ope = vai
= { cout<<‘a= "<a; Ni
] A obj; //objoct of class & 3
{ihe private data of class A is accessed in class B
q 1/ data contains § and x contains 2
rotumn obji.data ~ x; m
} K
) outer obj; ©
outersinner obj2;
2.14 : Nested Class
= obj2.fun(S0bj1,10); //invoking the function of inner class
LAZTG What Is nested class ? Write a C++ program to demonstrate
the concept of nested class. }
Ans. : When one class is defined inside the other class then it is called ie
the, nested class, The nested class can access the data member of the Output
outside class. Similarly the data member of the nested can be accessed a= 10
from the miain, Following is a simple C++ program that illustrates the use
of nested class. a
<
——
ss A Guide for Engineering Students
Ss
"A Gul for Eg
se a a aip maents
Inheritance and Pointers
ted Programming 2-25
represents the memory
location of some other variable, The purpose of pointer is to hold the
memory location and not the actual value. For example «
toring some value in a*/
jetting value from address in ptr and storing it in b*/
2.16 : Memory Management : New and Delete
lain the purpose of new and delete operators with suitable
‘The dynamic memory allocation is done using an operator new.
int *p:
penew int;
locate the memory for more than one clement. For instance if
locate memory of size in for 5 elements we can declare
For example
ints};
‘The memory can be deallocated using the delete operator.
For example dotote p:
C++ Program using new and delete operators
int main ()
{
{nt in;
int *p;
~ cout << “How many numbers would you like to type? ":
cin >>
P= new int[ij//dynamic memory allocation
Hf (p == 0)
Goes ‘A Galde for Engineering Soudents
Inheritance and Potters
Object Onented Programming 2-26
cout << "Error: memory could net be allocated";
tse
for (n=0; nck: n+)
«
cout << “Enter The Number: "
in >> plat
for (n=0; neti n+
<<" <getVall)< mim=num;
}
void print_val()
{
cout<<"\n The value i "<
using namespace st
void ming
{ is
int aft0), jn. “pte keys
cout<<"\n How Many slaments are therein an array ?
cin> >;
cout<<"\n Enter the elements in an array
for = 0; ens i++)
cin> >a
1 Guide for Engincerng Suesject wning 2-29 Inheritance and Polnters
"copying the base address in ptr */
cout<<"\n Enter the Key element *
cin> >key:
for (= 0; fens i++)
£
Apter == key)
‘
cout <"\n The element is present "
break;
>
else
ptr++; /*pointing to next element in the array*/
[Or write ptr=ptr+i*/
2.21 : Pointer Arithmetic
2.23 Explain various pointer arithmetic operation:
Ta [SPU : Dec, Marks 4)
Ans. : Pointer arithmetic means performing arithmetic operations on
pointers. Following are various pointer arithmetic operations -
desired
“| eper=ped
erro oo —_
4 The pointer variable can be incremented or
Meaning
| ‘Multiplication of two poiater variables is possible in
this way.
‘The subtraction of two pointer variables,
pols = or pil
I decremented
pe eee
‘We can add some constant to polnter variable.
se pil=I0
| aspii-20 We can subtract a constant value from the poatr.
—S———
ecooes ‘A Gulde for Engineering Students
Object Oriented Programming 2-30
Inhertance and Pointers
‘Tue telatonal operons are posible on poiter |
variable whule comparing sw pointer.
2.22 : Arrays of Pointers
2.24 What Ia array of pointers ? Explain with prendo code.
‘Ans. ; The array of pointers means the array locations are containing the
address of another variable which is holding some value. For example,
65524 66522 65520 ]
ee
cssn zDD
Fig. 0.26.1 Array of pointers
“The array of pointers is the concept which is mainly used when we want
to store the multiple strings in an array. Here we have simply tken the
integer Values in three different variables x, y and 2 The addresses of
y and z are stored in the array a, This concept is implemented by
{following simple C++ program,
#include
using namespace std:
void main()
{
Gute for Engineering SessObject Oriented Programming 2-31 Inheritance and Poaters
cout<<"\n Enter The Array Elemente ”;
ela >x>>y >> x
810] = &ax/*storing the addross of each vasiable in erry location */
alt} = ay:
-<" is at location "<
28 Write program to find the sum of an array Arr by posbt
fan array to a function using pointer. ES (59P0 : Decl), ted
Ans,
‘sing namespace sta;
Int fun(const int ‘arr, int size)
4
‘ot sum = arr
for (int i= 254 < alze; +44)
s A Gulde for Enger
JZInheritance a
2 ind Poy
EN Poin
has float parsineter ang
ter to the function
meter to another
ay Arr by passing
2s Deea7, Marks 4]
——_
Tnameering 5
‘
sum = sum+ “(enr4i)
‘nt main
const int SIZE = 5;
{nt sumbers(SIZE] = (10, 20, 90, 76, 22};
cout << “The sum of array is: "<
‘using namespace etd:
vold display(foat("tptein), i 2)
4
{Meall to pointer vo function*/
cout< <"\n The area of circle is "<(*fpt
2.24 : Pointers to Pointers
0.28, What is pointers to pointers ? Explain.
‘Ans. ; A pointer ean point to other pointer variables which brings tbe
multiple level of indirection.
vvold main()
t
ee
“A Guide for EngineringStdensObject Oriente Programming 2-35 Inheritance and Pointers
= 10
pint = a
cout<<"\n *pi? = "<<*ptr2i/etoring address of ptr1*/
cout<-<"\n pird = "<
using namespace std;
class Base
— “Gu for Enginwrng Sunt
on 2.
jee onented Progress ——— = Uhere
pues Or sothing.
+ NULL p
public:
ct
ms includ
void display”) ‘void ma
4 on conan eee ce te
, m=
» on
ts mano ;
‘
Derived obj : on
Seswe ops; olntr to derive 7
ee Powe
eves 300
pooh = 20
pues ax
: fre
output na
=
“to
seme manta damage. For this eso
The sanded intlization ito the constant NULL 7
Using the NULL value as a pointer will cause an error on aims)
systems,
=—S—_—_—_——
qecones e
“A Guide for Engineering Se®them.
st all
(dent
stropy(str, HelloFriende’);
cout [sr
‘Ams. : Operator overloading can be defined as an
‘meaning for an existing (built-in) “operator”,
How to overload operator 7
Define a fiction with keyword operator. Then write the operator(such as
‘+ [] or any other valid operator ) as a function name, That means we
‘can program that specific operator.
+ You can not redefine ::, sizeof, ?: ot « (dot).
Q5 With suitable examples, demonstrate the benefit
overloading. = [SPP
‘Ams. + Due to operator overloading, an operator will not be limited to
work only with primitive data Type but it can perform operation on user
——————————
z “A Gulde for Engineering Sade,
a
fame ~ ve oan aaa
For eae ected + oper,
3 without paramete
=0;q=0;}// constructor wit Sm
oar: cuca with parameters
(t (wector);//definition of operstor +
voctor:vector (int a, int B) {
pam
ah
y
vector vectoroperator+-(vector obj)
4
vector tempi }
vempp = P + ODP:
temp = 4 + obj.G: int matn( )
retum (temp); {
y inex y
int main ()
vector €;
caath
cout<<"\n The Addition of Two vectors is."
cout << ep <<" and "<
cutput
Enter the co-ordinates x and y 10 20
‘The increment operator increments the co-ordinates as.
1, ¥: 22
Q.7 Write a program to overload
1, Operator + for concatenation of two strings.
2. Operator >> for reversing a given string.
3, Operator << for displaying a given string.
1a [SPPU : May 2086, Marks 6)
Ans.:
class StringClass
«
public
char str{30};
StringClass operator+(StringClass 51)
y
friend ostream& operator<<(ostream &outt, StringClass &s1)
{
outt <<"\nString: "<< si.str
return outt;
}
friend istroamé operator> > (stream &inn, StringClass &51)
eases A Gute for Enginecring Soden's+ (obj.1mg*ob}.imgy,
‘obj.img))/new temp:
cin >> e4://invokes >> operator for string reversal
)
Q.8 What ts operator overloading ? Overlosd the _sumerical
Operators + and / for complex numbers addition and division ato!
respectively. with
‘Anse: Operator overloading is defined as an ability to define + new oe
meaning for an existing operator come
/*Program for overloading numerical operator + and / for i
complex numbers addition and division’/ fonvi
#include
using namespace std:
class complex { cout< <"\n The addition of two complex numbers is.
cout<> a>>b;
result = obj.sum(a.b}:
break,
ease 2: cout <<“\nEnter 8 numbers: "; echeae
cin >>a>>b>> ——
result = obj.sum(¢
break;
case 3: cout <<"\nEnter 4 numbers
cin >> a>>b>>o>>'d:
result = obj.sum(a,b,c,d);
break;
dofault: cout <<"\nWrong Choice";
break;
Q.15 What Is function overloading 7
‘example.
Ans. : Refer Q.13 end Q14,
16 Differentiate between function overloading and function
1s function overloading the
ignanure must be different for
reoaded functions.
‘tn function overloading, we can
hhave any number of overloeded
Functions.
——$
verng Suen
Srcoas “A Gulde for Engineering Students eerObject Oriented Programming 3-14 Polymorphism
—omeirrererming 3-14 Polymorphism
3.8 : Runtime Polymorphism
.17 Explain the concept of Runtime polymorphism in detal
Ana: Runtime polymorphism it” also known as, dynamic
phism ot late binding. In runtime polymorphism, the function
resolved at run time,
* The runtime polymorphism can be achieved by function overiding or
method overriding.
* Redefining a function in & derived class is called function overriding.
1 Coit for Enginering Sates
eo
wig 32
object Orient Program TT” a.
sic
peed meg) bog:
‘
bed:
3
void print_msg0)
c(10+20)= 30
Tm print_mag() in class A
(100-10) = 90
Tim print_mag() in clase BObject Oriented Programming 3-14 Polymorphism
3.8: Runtime Polymorphism
2.17 Baptatn the concept of Rene
7 ey Rontinepalymorphiam a etl
Ans: =) Rune pobmopbion imeem Im deta
phism or late binding In nntine pobmentien, he een
call is resolved at run time.
* The runtime polymos
“phism can be achieved overriding or
‘method overriding. ol
* Redefining a function in a derived el
C++ Program
#include
using namespace std;
class A
{
private:
int ab;
Public:
void get_msg()
{
a=10;
b=20;
}
void print_msg()const
{
lass is called function overriding,
int
o=a+bi//performing addition
cout<<"\n C(10420)= "<
using namespace std;
——
‘A Gulde for Engineering Sudener
Greoass
—ae
efor Engineers
Object Oriented Programming 3-37 Pelymorphiom
ee Oriented Propemming 3-7) _—Patyerphiom:
class Polygon {
class Rectangle: public Polygon {
public:
int aroat)
(totum width*height: }
x
class Triangle: public Polygon {
public:
int area()
{ xetum width"height/2; }Leet Oriented Programming — 3-28
Polymonphion
tual Function and its Significance in Cr+
riented Programming
cout «Tie “<<< cena
2s Spabtecion opal wince,
, oa
12 Book : public Media
publte:
‘int pages:
vital vold Read(int mum)
{
pase =
viral void show()
‘
cout << ‘Number of pages of book“
cout << pages << “\n"
}
>
Tie
Polnters tothe ‘base
public:
char Telo{10},publication(201;
| pial void Rs
ccout<<"\n Enter the title:
cin> > Tite;
‘cout<<"\n Enter the publication: ";
‘in> > publication;
}
virtual vold show()
“A Guide or Engineering Sinden
clase Tape : public Media
¢
publtc:
int playtime;
virtual void Read(int mum)
4
playtime = num;
a
virrual void ehow()
{
cout << ‘Playing time in tapes";
cout << playtime << "\n';—=
Saring Stes
ed Programming 3-20
Book by
objshow(
cout<<"\nEnter number of pages:
b Read(num)
Output
Enter the title : AAA,
Enter the publication : BBB
Tide: AAA
Publication : BBB
void dieplay()//overriden funtion
a 4
Enter number of pages : 100 cout< <"\n Derived Class Function’;
‘Number of pages of book : 100
Enter Time in minutes : 3
Playing time in tape : 3
class pointer
3.11 : Pure Virtual Function and Virtual Table
- for derived class
Ans. : Virtual Function and its need - Refer Q.20,
‘A pure viral finetion is a virtual function which is to be implemented
by derived class, The class that contains the pure virtual function is
called the abstract class.
—
“A Gide or Enginering Students a
Tutte for Enginering Suse{ cour<<"n Calling Base class Constructor; )
wirual ~Baso() /vtrtual destructor
{ coute<"\n Calling Base class Destructor}
class Derved:public Base
public:
Derived)
{ cou<<"\a Calling Derived class Constructor’; }
~Derived()
{ cout<<"a Calling Derived claes Destructor’; )
®
ft mind)
«
Base *obj=new Derived!
delete obj; //dertved cl
return 0:
“A Guid for Enginerng dens
derived class wil provide its own! redefinition,
END.5
“A Guide for Engincerng Soles
Programnin
The specific
level YO at
used as 2 t
basie_ostres
streams cep,
aMeaning
Standard input
Standard ouput
Standard eror
Buffer of enor
The header file named /ostream.h supports these UO operations.
4.2 : Stream Classes
L.A buffer system
the basic low level input output operations,
programming the basic_streambuf class is used di
fon system implemented by basic_t
‘that provides formatts
fen by basic_streambuf class. This class supports
advanced 1/0
ym and basic_iostream.
SE
1)
Object Oriented Programming 4-2 ies and Streams
3. A wanslation systems implemented by cenain classes like isveam,
0.24 Stream class hierarchy
4.3 + Stream Errors
3 Explain the commonly weed enor fonctions defined by fos
‘This functions returns tue if there Is 29 eTor
This function returns tre if no read/write operation is
sadiwrite operation is performed
operation is
“A Guide for Engineering Sovdetsbfect Oriented Programming 4-3
cout << “The good() function retums: * << cin.good):
‘cout << "Wp Correct inputs
cout << “\aThe good!) function retums: * << cin.good();
d
?
The above programm will gi
by the use.
ge if non integer value is entered
eo gieorng Suara
(A Guldfor Evgtncrng Sater
‘object Oriented Programming 4-4
etream ? Write
=
‘Ans: Refer Q.1 and Qe
‘4 : Disk File 1/0 with Streams
ae
ne
ee et eop 4
‘rom the files.
‘operations defined by fos. While using file UO we needs
lowing tasks -
input stream, declare an object of type ifstream.
‘an output stream, declare an object of type ofstream,
1.To
2. To
3. To create an inpuouput steam, declare an object of type fstream.
Q7 Explain various flags used in modes of file open operation
= rit
1¢ mode is optional parameter and is used with the fags
Open for input operation,
(Open for binary operations.
“A Gulde for Engineering Sule
as wito If this fag is set then initial pos
otherwise initial postion ie
Tositrune The contents of pre exist
by new dre,
ing file get destroyed and it is
28 Write 2 C++ program to rend the contents of a text he
2 -
#include
#include
#inchude
using namespace std;
int main()
U1 Print an error and exit
corr << ‘Sample.dat could not be opened for reading!" << endl;
exit(3);
t
cout<<"The Contents of the file aro..."<
inclose();
excons ‘A Gulde for Engineering Students
Object Oriented Programming 4-6 Files and Strains
Note : The Sample dat file is already created with the data as obtained in
above output
2 C++ program that reads a file
counts the number
es, words and charactere present In it.
char Datale0}
int we=0;
int co=0;
sat le=0;
ttstream in_obi
tn obj.opent(Odd.dar)
{n_objzead((char *)&Data.sizoofData));
whit(in_ob))
4
sn_obj getline Data.80);
int n=strlon(Data);
cot=n;
= ‘A Guide for Engineering Srdenscout <<"Whiting Data tothe svean..”<> valle
Soe cana Ete names
Sa >> same:
7c TN ne mae"
Gn>> mats:
}
old aispleyivoid)
ee
"a Guide for Engineering Ss!
senec ont Prorat
cas ced oo entection
wid exation oP
: as ae fe
Object rented Programming 4-11 Files and Streams ae
(manerer Samet <<(onoam tt Pint 2)
Cimon nope
1"; /fout the values
Ceo <1)" <ébhy << Houtpunting @
cee eraming 208
)
Irwaactr tune
(rena toperator>>
f rs
an /fmpurting the values
(stream &st, Point &obj)
at >> bhai
: cout << "Enter ¥:%
Foi StodentswitePiog —// Momber fonction for wt fle pga
a i aifay of char
The argvio]
is not avail
18 Write a short note on - memory as a stream object. ‘command fi
Sas. : e's Crt it is possible to teat particular section of memory sing
cow a st
el meer to tenes comaoay wel cute meg Mh
oars 2 sonas
+ Tp cen sit aay et Soracs
cntern Sedona ble vskar
vena cae
Q417 How de deci | f :
low do you jare an overloaded stream insertion and int RolINo = 10; a
‘itr St seta ee aac fae
+ In C++ the output operation is denoted us ‘<< whiet eran
erin pr Se se te < ih ae Char DetelSIZ; Data Butter for memory obj ee
using >> Sees
aS OS
foe eet aie "A Guide for Engineering Suetject.
om of memory as
memory with the
> create memory
”)
——
Engineering Studer’
‘nt main(int arge, char “argv{))
Here the are represents the total number of arguments and argy is a an
ajay of characters that store the command line arguments
‘The argv[0} is the name of the program, or an empty string if the name
is not available. After that, every clement number less than arge is a
command line argument. You can use each argv element just like a
string.
2.20 Write a C++ program to read the contents of the flle In
which the file name Is specified by command line argument.
Ans.
#include
#anclude
using namespace etd;
‘include
Int main(int arge, chee* axgvl) )
{
‘M{ arge = 2)
4
excoss ‘A Gulde for Engineering Students
cout << ch;
return 0;
»
4.11: Printer Output
2.21 Explain how C++ code Is used to send the output to the
ter
In C+ it is possible to tend data to the printer and print and get
the formatted output.
For exampl
‘aclude //for fle streams
‘using namespace std;
nt maing)
4
ofstream printer; /make a fle
printer open("PRN"); //open.
printer << "Hello fiendsill" << yend data to printer
printer << \x0C’; //formfoed to eject page
printer.close();
retum0;
"Guide for Engineering Suse
So eee|| Exception Handling and Templates
5.1 : Error Handling Techniques
Q.1 What are three commonly used error handling techniques ?
‘Ans.: Three commonly used error handling techniques =
1. Terminate the program on error situation
2 Write the error code and assign it to global variable. On getting the
cor, return the comespanding code,
3. Some starus code can be predefined and on success or faire the
comesponding code can be returned,
4. Use of goto for
desired statement
{ty represents the block of statem
there are chances of occuring some exceptional conditions,
When exception detected itis throvm using the throw statement,
(6-1)
Object Oriented Programming 5-2 Exception Handling and Templates
ject Ort
yents in which the exception thrown is
‘There exists a block of statem x
handled appropriately. This block is called eatch block.
For example
include
using namespace std:
int main
(
wy
t |
ow 100, | ‘Output
facets ‘An expection at 100
cateh (int x)
{
cout << “An exception at " << x << endl;
}
zoturn 0;
}
In above program the iy block contains the portion of the code for
‘exception handling,
‘The main advantage of exception handling mechanism is that any
causing situation can be gracefully handled by raising appropriate
exception without carshing the code
2.3 Explain exception handling mechanism in C++
TE [SPPU : May-a5, Marks 4]
Ans. : Refer Q2,
G4 What ts exception ? How Is an exception handled in C++?
5S [SPPU £ Decrt9, Marks 5}
Ans. : Refer Q.2. =
SSS
A Guide for Engineering Sudenson Hanaling and Tomy
the exception tro
block. wn ty
25 What Is the difference between e1
os, Tor and ax
Object Oriented Programming 5-3
Exception Handling and Templates
Sr. No.
1
Error cannot be handled.
Using exception hand,
Enor Is uncoverable, Exception Is cover
‘Output
expection at 100
ortion of the code for
anism is that any error
sy raising appropriate
c++
FPPU May-i5, Marks 4 1
vandied in C++ ?
SPPU 2 Deew39, Marks 8)
————
defor Engineering Soden
| Program crashes or stops Program repets user friendly
Wworklng when an error occurs, | message about the sbnonal
snuation and exits grocefly
5... Brot cannot be covered but it The exception can bo handled
fs fixed by the programmer. using ty, catch and throw
5) J) Error is compile time error. — | Exception is ran tne eot
5.3 : Divide by Zero
program to. ha
Jston operation using exception hand
cout << "Enter denominator :":
cin >> fi
——
eae
“1 Gule for Engineering Soden
Object Onented Programming 5-4 Exception Handling end Templates
old divide(double a, double b)
to==0)
‘throw bi // aivide-by-20r0
cout << "Reeult:" << a/b << endl; // for non zero value
}
cctch (double b)
4
cout << ‘Cant divide by 2010.0"
output
+ When an exception occurs then the control is transferred to the
block and at thet time my block is terminated. There can be multiple
‘exceptions in multiple eateb statements with one try block. Following is
f structure of the program when multiple catch blocks are allowed.
vvold function
{
wy
————_—_—_———————————————
aos “A Gulde for Enginering Sudentsbec Oriented Programming $-5
‘
,
exten datatypes arg)
«
)
‘ontch (datatype? arg)
4
Tie Pog ilrtming muliple cach semen is as shown below
Hesutiplo catch tor stage try block
atctnt 1)
Soo ‘A Guide for Engineering Sudenn
Exception Handing nd Templates
Exponent ed Tg,
Object Oriented Programming 5-6 <
<< “Exception for number is bandied: ° << { << "q,
os ‘A Gulde for Engineering Sudensjt Orne Prenming 5.3
rowing of the exception,
Following program shows the ret
Pichude
throw “myworld”
ceatch(char*)
cout <<"\nlnside the catch statement of fusccion)*
s f fucerion(,
throvr //rethrowing the exception
cout<<"\n\ninside the catch statement of main()";
}
return 0;
)
oe “A Guide fo Empinerng Sodens
gineering Suter
Object Oriented Programming 5-8 Exception Handling end Template
5.6 : Exception Specifications
vol maind)
‘
wy
the integer value “
#include
‘using namespace std:
11 Catching class type exceptions.
class My_Bxception
{
public:
‘char s27(50};
iat mum;
My Exception) { "str = 0; mum = 0; } // constructor
‘My_Exception(char *s, inti)
hestiog {the number is positive or not
ny
cout << “Enter a positive number:
cin >> a
Ma<0)
throw My Exception(it's a negative number’, a);
else
oUt <<"It's a positive number'<< endl;
es
A Gulde for Engineerlng Students
ee
an
:
ee
ee
autre» ay mom so comput ts ot
Dumber, the user defined function mysqrt) should raise exception,
‘
#include
void MySqrt(double val)
{
uy
{
if (val < 0.0)
throw "Negative’;
else
cout << "The sqrt of *< >num;
MySart(num);
retumn 0;
Output
Enter some number: -5
Can not handle Negative number
5.8 : Processing Unexpected Exceptions
12 Justify the statement - “An unexpected exception le
in C++" = aan
Ans. : For processing the unexcepted exception, the set_unexpected
function is used . This function is also called as unexpected handler
function. The unexpected handler by default calls the terminate function,
void myunexpected ()
{
corr< “unexpected called\n";
throw 0;
Exception specification lists int
and double values.
}
void functi
{
throw(“Hello");
} ‘The string is not specified in the list
void main() hence unexpected exception occurs.
{
unexpected
set_unexpected (myunexpected);//eetting wnexP
Hexception handler
i
Guise or Engineering Siders
eeont 4
PE eee eee tree eer trier eee
Object Oriented Programming $~12 Exception Handling and Templates
——e ing S712 _ Exception Handling and Templates
‘hy block calling function()
Heateh block.
)
5.9 : Constructor, Destructor and Exception Handling
43 How does exception handing activity Is carried out when
constructor and destructors are present In C++ program ?
‘Ans. : When the exception is raised inside a try block, for all the
objects ereated inside the blocks the destructor is called first and then the
catch bldck executes to handle the exception raised in try block.
mple
public:
Tost() { cout < "\n Constructor is calle
~Test() { cout < “\n Destructor is called”; }
k
nt main()
then catch block executes
catch (int e)
{ cout < NnBxception is caught” <6; }
retum 0;
)
“H Gulde for Engineering Sodens
———————Exception Handling and Templates
Object Orbented Programming 5-13
‘5.10 : Exception and Inheritance
vold main
‘
Da:
uy
{ throw di: }
catch (B cbf)
{( cout < “\n Base class Exception handling catch block”; }
WHexception gets handled
Wby Base class
catch (D obj)
{cout < “\n Derived class Exception handling catch block"; }
5.11 : Introduction to Templates
code fr any date type demens. The template is wed ws 4 wot fe
generic programming,
Templates allow the reusability of the code. There are two categories of
term
1. Function template 2, Class template
SS
object Orlented Programmnins.
3.2 : The Power of Templates
+The Stand:
written as templates
1¢ object code
«It helps in generating high performance obj
lard Template Library(STL)
templates, in which the commonly used
class T
T min(T a, Tb)
«
if (a ne
vold display(T x)
{
cout << x;
)
void display(int a)
concept of
unctions are
‘The function body will differ in function overloading whereas the function
body will not differ in function template.
si << nn non apes
pt they are } y
int main() _
; hse
y
cout << *\n Displaying string: "; : ca
«tan temp, tf, tin
scone aug. tee tome fr, Saas
‘cout << "\n Displaying floating number: *; Ans. : Refer Q.19.
displ 55);
5.15 : Class Template
cals overoeded non tamplts function
What is clae tempat ? oe
aaa Using class template we can write & class whose members ust
fe parameters a5 TYPES,
—S—— ss
(A Guide for Enginearing Students | a
——————Exception Handling and Templates
For Example
f template
t class Compare { //writing the class as usual
T a, bi//aote we have used data type as T
public:
Compare (F first, T second)
{
anfirst; ©
besecond:
»
‘T max 0//Snds the maximum element among two
k
‘/hemplate class member function definition
/Mnore the member function of template class is max
template
‘T Compare max ()
int main ()
{
Compare ot
cout<<“\n meximum('p',
=P obj2.m
rotrun 0; j2.max();
A Guide fr Engineering Stadens
nject Oriented Programming 5-18 _ Exception Handling end Templates
5.16 : Template Arguments
ait exin temas memes with Depo hint
example. ete
Seem ne mie ssn.
a en eh Be aa mT oo
sea sm pr ome we ven
‘a tee
Tt gt Pn ost oe cd
ip int
Following program illustrates this concept -
#include
using namespace std;
template
Compare
ting the class as usual
. bi//mote we have used data type as T
public:
Compare (T first, int second);
T max ();//finds the maximum element among two
hk
Jheroplate class member function definition
{sere the tember function is constructor
‘template
Compare::Compare(T first, int second)
{
a=first;
b=second;
+
‘Moers the member function of template class is max
template
T Compare imax ()
——————— ee
Seco ‘A Gulde for Engineering Sniden's
A1d Temp
as
Mustrative
uments are
"6 Can also
define the
ad secong
oe sniien®
Perle Programming 5-19 Bae
E_S°19 Exception Handing and
{ eins ad Template
val
a>d)
val=a:
val=b;
return val;
int main ()
ii
Compare obj1 (11
cout <<"\n maximum(1
return 0;
160}i//comparing twe integers
160) = "<
using namespace std;
template clase C //integral expression
{
g TA Gulde for Engineering Sudens
220 Exception Basing.
Q.24 What is C++ template ? Describe type and non type
EB (SPPU Dees, Mats 8)
Q21 and Q23
5.18 : Template and Friends
0.25 How to use friend function along with templates ?
‘Ans. : A fiend function can be used within 9 template class
Following C++ program Ulustrates how to use frend function inside
the template class,
#inchde
using namespace std:
template
class Test
4
template fiend void f(Test
“Tne for Engineering Saten
cro