OBJECT ORIENTED
PROGRAMMING
introduction to OOPs
Object and Classes
Operator Overloading
Inheritance
Polymorphism
Files & Streams
Exception Handling & Templates
NOTE:
MAKAUT course structure and syllabus of
OBJECT ORIENTED PROGRAMMING has been introduced as a new subject in
Present curriculum, Taking special care of this matter we are providing model
jea about university questions
Questions & answer, so that students can get an ide
Patterns. :
6 semester has been changed from 2021
10
58
83
97
128
137POPULAR PUBLICATIONS
INTRODUCTION TO OOPS
4. What will be the output of the following piece of code? [MODEL QUESTION)
#include < iostream.h >
define a 2;
int main()
t int j =37
int isatj++;
cout<< i;
return 0;
y
2} Compilation error) 6 °)5 a4
Answer: (a)
2. What will be the output of the following? [MODEL QUESTION]
#include
int main ( ) (
int x = (10, 013);
cout<<"ner
int val = 30;
int & £ ( ) (return val;)
int main () (
Gout <<"Val=” MAREE AUESTION
int main() {
int x = 10;
int y = 20;
if ( ((x++)>10) & (++y))
COUR K [MODEL QUESTION]
using namespace std;
void main ( )
void main ( )
(
)
cout << “hai”;
int main ( )
{
main (
return
a) hai b) haihai
¢) compile time error d) none of these
Answer: (c)
8. What is the output of this program?
[MODEL QUESTION]
4include
Using namespace std;
enum test {
A = 32, B, C
7 main ( )
cout << A << B << C7-
ae 07) ) 329292 ) 323130 d) none of these
Answer: (a)
oopP-3POPULAR PUBLICATIONS
9. What is the scope of the variable declared in the user defined function?
[MODEL QUESTION}
a) Whole program b) Only inside the { } block
¢) Both (a) and (b) d) None of the mentioned
Answer: (b)
40. Which of the following features supports reusability and extensibility of
classes? [MODEL QUESTION]
a) Inheritance b) Overloading c) Polymorphism d) none of these
Answer: (a)
Ae is the ability for a message or data to be processed in more than
one form : [MODEL QUESTION]
a) Class b) Abstraction ¢) Polymorphism d) None of these
Answer: (c)
12. A collection of variables referred under one name is [MODEL QUESTION]
a) structure b) class ¢) union d) none of these
Answer: (a)
43. y = x=2; in C++ will result in [MODEL QUESTION]
a) compilation error b) runtime error
c) assignment of value toxthentoy d) none of these .
Answer: (c)
14. Which of the following is a valid statement in C++? [MODEL QUESTION]
a) int x= (int) 2.50; b) int x= int (2.50);
c) both (a) and (b) 4d) none of these
Answer: (c)
15. Which data type is used to represent the absence of parameters?
[MODEL QUESTION]
a) Int b) Short ©) Void d) Float
Answer: (c)
16. When will the cin can start processing of input? [MODEL QUESTION]
a) After pressing return key b) By pressing blank space
c) Both (a) and (b) d) None of these
Answer: (a)
17. A macro is processed by [MODEL QUESTION]
a) compiler b) interpreter ¢) pre-processor —_d) none of these
Answer: (c)
48. Which of the following is not a feature of OOPS? [MODEL QUESTION]
a) Encapsulation b) Inheritance ©) Static binding d) Polymorphism
Answer: (c)
OOP-4OBJECT. ED PROGRAMMING
43, The design of classes in a way that hi
10 ear le knowrivas ides the details of implementation from
JODEL QUESTIOI
a) encapsulation b) data hiding ¢) data abstractie” d) all athe,
Answer: (a)
20. Which of the following programming technique focuses on the algorithm?
[MODEL QUESTION}
b) Object oriented language
4) Structural language
Short Answer estions
1. What are the basic features of Object-Oriented Programming?
How does it differ from Structured Programming Concepts? [MODEL QUESTION]
Answer:
Object oriented programming propagates a slightly different approach to programming
problems than the strategy which is usually used in procedural approach, where a
problem is decomposed into sub problems and this process is repeated until the subtasks
can be coded. Thus a conglomerate of functions is created, communicating through
arguments and variables,
In contrast, or maybe better, in addition to this, an object-oriented approach identifies the
keywords in the problem. These keywords are then depicted in a diagram and arrows are
drawn between these keywords to define an internal hierarchy. ‘The keywords will be the
objects in the implementation and the hierarchy defines the relationship between these
objects. The term object is used here to describe a limited, well-defined structure,
containing all information about some entity data types and procedures to manipulate the
data. This concept is shown in the Figure.
a) Procedural language
c) Object based language
Answer: (d)
Object |
data
Object 4
data
Object 3
data
‘Object 2
data
Program |
ing, Objects of t
rrvages to each othe.
he program interact by sending
Object oriented program
messages t
oopP-5PULAR PI |ONS
Basic features of Object Oriented Programming:
Emphasis is on data rather than procedure.
Programs are divided into what are known as objects,
Data structures are designed such that they characterize the objects.
Functions that operate on the data of an object are tied together in the data
structures,
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through functions
New data and functions can be easily be added whenever necessary
Follows bottom-up approach in program design.
2. What do you mean by a reference variable?
Is there any difference between reference variable and pointer? Explain with
example. [MODEL QUESTION]
Answer:
C++ references allows to create a second name for the a variable that one can use to read
or modify the original data stored in that variable. what this means is that, when some one
declare a reference and assign it a variable, it will allow to treat the reference exactly as
though it were the original variable for the purpose of accessing and modifying the value
of the original variable--even if the second name (the reference) is located within a
different scope.
Example:
int x;
int &y = x; // Here, y is the alias or second name of x.
A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a
reference shares the same memory address but also takes up some. space on the stack.
Since a reference has the same address as the original variable itself, it is safe to think of
a reference as another name for the same variable.
Example:
intx=5; int y=6; int &r
intx=0; int &r=x; int *p=&x; int *p2 =r; assert(p == p2);
3. How would you create space for an array of objects using pointer? Give
example. [MODEL QUESTION]
Answer:
As an array of variables can be declared, similarly one can also declare an array of
objects and manipulate each member of the array as if it were a regular variable. To do
this, type the name of the class, followed by a valid C-++ name for the variable, and
followed by a dimension included in square brackets. Here is an example:
#include
using namespace std;
struct Point
{
char Letter;
OOP-6OBIEC
RIENTED PROGRAMMING
int x;
int yi
h
gnt main()
{
Point coordinates (4);
return 0;
Instead of using one pointer to an obj
The syntax used is:
className *VariableName (Dimension);
ject, you can declare an array of pointers to object.
The ClassName must be an existing object, You can use your own object or one that
shipped with the compiler. After the asterisk Operator, type a valid name for a C++
variable. The dimension, which is (an estimate of) the number of elements of the array, is
included in square brackets
After declaring the variable, you can initialize each member of the array using the new
operator. This operator allocates enough memory space for the member of the array. This
means that the initialization with the mew operator can be followed by an actual
initialization of the member variables of the array.
To initialize a member of the array, you have various options. You must first call the new
operator for each member of the array. Once again, you can use one of the constructors.
Consider the above Cone object. We saw that one of its constructors took two arguments
{0 create an object. You can use such a constructor to initialize a member of the array.
Here are examples:
Header File: cone.h
#ifndef Cone
‘define ConeH
Private:
double _rad;
double Lhgt;
Piblies 9
Cone () ;
Cone(double radius, double height);
Cone(const Cone& ¢);
~Cone();
Void. setRadius (const doub.
Void setHeight (const doub:
@ouble getRadius() const
le radius) { rad
le height) ( _hot
{ return _rad; ) :
oOoP-7
nuPOPULAR PUBLICATIONS
double getHeight() const ( return _hgt; }
double CalculateBaseArea() const;
double CalculateLateralarea() const;
double CalculateTotalarea() const;
double CalculateVolume() const;
Pointers to Arrays of Objects:
#include
#include *cone.h"
using namespace std;
int main()
{
Cone *pCone [3];
pCone[0] = new Cone(25.55, 20.15);
pCone[1] = new Cone(12.44, 18.62);
pCone[2] = new Cone(48.12, 38.84);
cout << "Cone's Characteristics\n";
for(int i = 0; i <3; i++)
{
cout << "\n - Cone No. "<< i +1 <<" =";
cout << "\nRadius: " << pCone[i]->getRadius();
cout << “\nHeight: " << pCone[i]->getHeight();
cout << "\nBase Area: " << pCone[i]-
>CalculateBaseArea () ;
cout << "\nfotal Area: " << pCone[i]- a
>CalculateTotalArea();
cout << "\nTexture Area: " << pCone[i]-
>CalculateLateralarea() << endl;
}
return 0;
}
4. Why are cin and cont not considered as keywords? Explain the role of streams
C+, [MODEL QUESTION)
Answer:
Keywords are predefined reserved identifiers that have special meanings. They cannot be
used as identifiers in your program. Most C-+ keywords allow to do one thing, We can
use int to declare an int, or that a function returns an int or expects an int as an argument.
We can use new to allocate memory, and delete to free memory. We can use const t0
indicate that a variable’s value cannot be changed.
But the case of cin and cout are not the same. They are called as streams. A stream is an
abstraction that represents a device on which input and output operations are performed.
A stream can basically be represented as a source or destination of characters of
indefinite length.
OOP-8OBJECT-ORIENTED PROGRAMMING
Streams are generally associated to a physical source or destination of characters, like a
disk file, the keyboard, or the console, so the chat ‘
i ‘ acter
abstraction called stream are physical! tS gotten or written to/from our
7 ly input/output to thi sit i
Gara ar Cec mane id een See See
used to open a file, any input or output operation performed on that stream is physically
reflected in the file.
Another important point is the keywords functionality are not defined in some header file
Their functionality are constant and are integral part of the compiler. But in case of the
stream they are like predefined methods, whose functionality are defined in some header
file. In order to work with them, inclusion of such headers are compulsory (where the
prototypes are declared).
Long Answer Juestions
1, Write short note on ADT. [MODEL QUESTION]
Answer:
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions, which are wrapped in the class,
can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data
hiding or information hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as-size, weight and cost, and functions to
operate on these attributes. They encapsulate all the essential properties of the objects
that are to be created, The attributes are sometimes called data members because they
hold information. The functions that operate on these data are sometimes called methods
or member functions.
Since the classes use the concept of
Types (ADT).
data abstraction, they are known as Abstract Data
oor-9POPULAR PUBLICATIONS
OBJECT AND CLASSES
1. Aclass is a/an.... ... for an object. [MODEL QUESTION]
a) object »b) instance c) template d) none of these
Answer: (c)
2. Amember that can be accessed before any object of its class created is called
[MODEL QUESTION]
a) Static member b) Static method
c) Instance Variable d) None of these
Answer: (a)
3. In protected derivation, accessibility of base members undergoes the following
changes in the derived class. [MODEL QUESTION]
a) public becomes protected b) public becomes private
c) protected becomes private d) private is not inherited
Answer: (a)
4. A class has one data member and one method member. This class is used in a
program that declares ten objects of this class. The numbers of addresses for data
member and method member are respectively [MODEL QUESTION]
a) 10 and 1 b) 10 and 10 c) 0 and 10 d) none of these
Answer: (d)
5. Constructors can be [MODEL QUESTION]
a) Virtual b) Return type ©) inherited
d) generated by default if not provided by programmer
Answer: (d)
6. Private member of the super-class [MODEL QUESTION]
a) is both extended as well as accessed inside sub-class
b) is extended but cannot be accessed inside sub-class
c) is not extended but can be accessed inside sub-class
d) is not both extended as well as accessed inside sub-class
Answer: (b)
7. The difference between new operator and malloc() is that. [MODEL QUESTION]
a) more memory space is allocated in case of new operator
b) matloc() allocates space dynamically
c)_new can be overloaded
d) malloc() can allocate memory space for any type of data
Answer: (c)
OOP-10OBJECT-ORIENTED PROGRAMMING
8, Which of the following operators is used to bind the functions to the class to
wc enmeion b) [MODEL QUESTION]
a)~ :
‘oy d) none of these
Answer: (C)
9, Which of the following statements is correct?
a) Destructors have a default value
b) Destructors can take arguments
c) Destructors deallocate memory allocated for the project by the constructor
d) None of these
Answer: (c)
[MODEL QUESTION]
10, When is the call by reference method used? [MODEL QUESTION]
a) Vaiues of the original variables are to be changed
b) Memory needs to be properly utilized
c) Both of these
d) None of these
Answer: (d)
11, Which operator frees memory previously allocated using new?
[MODEL QUESTION]
a) Free b) Malloc c) Delete d) None of these
Answer: (c) é
12. A friend function can be called [MODEL QUESTION]
a) by using object of the class b) should not be called -
c) by using the class name d) directly like normal function
Answer: (d)
i DEL QUESTION]
13. An obj Jan... .. fora class. [mot
a) ‘smptete oe b) friend c) instance ) none of these
Answer: (c)
i : MODEL QUESTION)
14. Consi statements: ; Iv :
TA reference variable provide an alias to a previously defined variable
Il Friend function can only be declared in the publle section
Ill A static member function does not nave is! p
¥ |V. New operator canhot be overioatetue?
Mehaf he taowing een i” lane’ None otha
ly
Answer: (b)
MODEL QUESTI
16. Constructor can be t ON)
a) virtual é
») with only return type vol
©) generated by default ifn
4) none of these
Answer; (d)
ot provided by the programmer
oop-11POPU JBLICATIONS
16. What will be the output of the following code? [MODEL QUESTION}
Class XYZ { int x;
Public: void func () delete this; } };
main () { XYZx; x. func ( ); }
a)runtime error b) compilation error ==) no error _~—d) nothing
Answer: (b)
17. Which of the following is false? [MODEL QUESTION]
a) In C+# no static variable can be member of a union
b) In C+ static member function may not be virtual
c) In C++ a union can have virtual member function
4d) All of these
Answer: (c)
18. Which is the default access specifier of a structure in C++?
[MODEL QUESTION]
a) Private b) Public c) Protected d) None of these
Answer: (a)
19. Choose the correct statement regarding static member, variable:
[MODEL QUESTION]
a) Declared inside the class, initialized outside the class
b) Need an object to access it
c) Inherited in sub-classes
d) Only can be used in static member functions
Answer: (c)
20. Friend function is used for [MODEL QUESTION]
a) accessing the public member of a class
b) accessing the private. member of a class
¢) accessing the protected member of a class
d) none of these
Answer: (a), (b), (c)
21. If a method is an interface between outside world and a class, it has to be
declared [MODEL QUESTION]
a) Private b) Protected c) Public d) External
Answer: (c)
22. A constructor is called whenever [MODEL QUESTION]
a) an object is used b) an object is declared
c) a class is declared d) aclass is used
Answer: (b)
OOP-12OBJECT-ORIENTED PROGRAMMING
3. Suppose a class “Box” is derived from a base class “Square”. When we create
an object of "Box class, then MODEL QUESTION]
a) it will first call the “Box” cla i ”
Me nictoe SS constructor then the “Square” class
it will first call the “Square” clas 2
S “
constructor: constructor then the “Box” class
c) it will only call the “Box” class constructor
d) none of these
b
‘Answer: (b)
24, The ability to declare different methods with the same name in a class is known
as [MODEL QUESTION]
a)overloading _b) overriding ¢)recursion _d) none of these
Answer: (a)
25, What value must a destructor return? [MODEL QUESTION]
a) a pointer to the class b) an object of the class
c) destructors do not return a value d) none of these
Answer: (c)
26. Copy constructor means [MODEL QUESTION]
a) parameterized constructor b) receives no argument
¢) receives object as an argument d) none of these
Answer: (d)
[MODEL QUESTION]
27. Goal of Data Abstraction is
a) Class formation
¢) Hide implementation details
Answer: (c)
b) Object formation
d) none of these
28. int : [MODEL QUESTION]
Inline functions are b) functions declared within a class
a) fi i lared in one line . m
a) functions declared i 6” function d) functions dectared outside a class
Answer: (a)
parameterized constructors and having no
we create an object that needs a zero-
[MODEL QUESTION]
29. What happens when a class with i
default constructor is used in a program an
argument constructor?
ile-ti b) Preprocessing error
i Cinhee eet a) Runtime exception
Answer: (d)
30. To hide a data member from the program, you must stectara the daty member in
the .. section of the class. hidden 0 QUESTION]
a) concealed b) confidential °) ih
Answer: (d)
ooP-13POPULAR PUBLICATIONS
34. How many times a static member variable is initialised? [MODEL QUESTION}
a)0 b)4
c) Depends on the number of objects created —_d) None of these
Answer: (b)
32. Consider a class called matrix with object mat and the declaration: const matrix
mati(x, y); Which of the following statements is false about this statement.
[MODEL QUESTION]
a) The values of x and y can be modified
b) The object mat can call only non-const member functions
¢) Both (a) and (b)
4d) None of the above
Answer: (a)
33. When a base class is inherited by a derived class as protected, the private
members of the base class become [MODEL QUESTION]
a) private member of the derived class
b) protected member of the derived class
¢) public member of the derived class
d) they cannot be inherited
Answer: (d)
34. The order of execution of base class constructors for the class declaration
class C: public B, virtual public A is IMODEL QUESTION]
a) derive, base, virtual base b) base, derive, virtual base
¢) virtual base, base, derive 4) virtual base, derive, base
Answer: (c)
35. Default visibility mode of a class is [MODEL QUESTION]
a) Public b) Private ©) Protected d) All
Answer: (b)
36. “this” pointer points to the object that is [MODEL QUESTION]
a) declared b) destroyed
c) currently unused d) currently used
Answer: (d)
37. When are the Global objects destroyed [MODEL QUESTION]
a) when the control comes out of the block i
b) when the program terminates
¢) when the control comes.out of the function
d) as soon as local objects die :
Answer: (b)
in which they are being used
in which they are being used
38. Which of the following statements is correct? [MODEL QUESTION]
a) destructors have a default value
b) destructors can take arguments
OOP-14OBIECT-ORIENTED PROGRAMMING
c) destructors deallocate m
@) none of these lemory allocated for the objects
‘Answer? (C)
39. If you define the constructor i i ; .
of that class. Options are: in the private section and try to create the object
a) it gives the syntax error “ [MODEL QUESTION]
b) it gives the run time error
¢) needs to define a proper static functions
d) none of the above
Answer: (a)
40. Which of the following type of class allows only object of it to be created?
ss [MODEL QUESTION]
a) Virtual class —_b) Abstract class ¢) Singleton class —_d) Friend class
Answer: (C)
41. Which of the following statements is correct? [MODEL QUESTION]
a) Base class pointer cannot point to derived class
b) Derived class pointer cannot point to base class
c) Pointer to derived class cannot be created
d) Pointer to base class cannot be created
Answer: (b)
42. Which of the following concept of oops allows compiler to insert arguments in
a function call if it is not specified? [MODEL QUESTION}
a) Call by value b) Call by reference
¢) Default arguments d) Call by pointer
Answer: (c)
43. Which of the following concepts provides facility of using object of one class
insi [MODEL QUESTION]
inside another class? Se T
a) Encapsulation b) Abstraction c) Composition d) Inheritance
Answer: (c)
[MODEL QUESTION]
let t?
44. Which of the following statements is incorrect
a) The default vale for ‘an argument can be a global constant
q jiven in the function prototype
3 Compiler ‘inoe the. nr cotyp “information to build a call, not the function
4) rhe ata It arguments are given in the function prototype and should be
e defaul
repeated in the function definition
Answer: (d)
oop-15POPULAR PUBLICATIONS
45. Which of the following statements is correct? [MODEL QUESTION}
a) Destructor destroys only integer data members of the object
b) Destructor destroys only float data members of the object
c) Destructor destroys only pointer data members of the object
d) Destructor destroys the complete object
Answer: (4)
48. What will be the output of this program? [MODEL QUESTION]
#include
using namespace std;
int array1 [ 1 ={1200, 200, 2300, 1230, 1543}
int array2 [ ] =({12,14,16,18, 20}
int tmp, result = 0;
int main ( )
e
for (temp = 0; temp < 5; temp++) t
result += arrayl [temp];
;
for (temp temp < 4; temp ++) {
result += array2 [temp];
cout << result;
return 0; }
a) 6553 b) 6533 ¢) 6522 d) 12200
Answer: (b)
47. What will be the output of this program? [MODEL QUESTION]
# include
using namespace std;
int main ( )
{
int array[ ] = {0, 2, 4, 6, 7, 5, 3);
int n, result = 0;
for (n=0; n<8; nt+) {
result += array[n];
x
cout << result;
return 0;
d
a) 25 b) 26 c) 27 d) None of these
Answer: (d)
48. What is the output of this program? [MODEL QUESTION]
#include
include
using namespace std;
OOP-16QBIECT-ORIENTED PROGRAMMING
jot main( )
struct student ¢
int num;
char name [25];
ve
student stu;
stu.num = 123;
strepy (stu.name, “John”) ;
cout << stu.num << endi;
cout << stu.name << endl;
return 0;
a) 123
john
b) john
john
c) compile time error
d) none of the mentioned
Answer: (b)
49. Functions can return IMODEL QUESTION]
a) arrays b) reference ©) object d) all of these
Answer: (d) :
50. The memory for member functions is allocated [MODEL QUESTION]
a) when a class is defined b) when an object is created
©) when an object is initialized d) none of these
Answer: (a)
51. A class having no public constructors is : [MODEL QUESTION]
a) a private class b) a public class
¢) an abstract class d) none of these
Answer: (a)
82. What string with blank space? = [MODEL QUESTION]
a) Ini ine ee ‘Dh eotine c) Putline d) None of these
Nswer: (b)
83. Whi ing is not a type of constructor? -[MODEL QUESTION]
optic
f these
Ang’) One argument constructor a panes
SWer: (c)
*. Object oriented Technology's use eran ath aMI ee small
ides system 08 85a
on 2hitecture and its snr
"ge in requirements does ie reaure massive changes in the system.
OP-17POPULAR PUBLICATIONS
[MODEL QUESTION)
a) encapsulation; inheritance b) inheritance; Polymorphism
¢) inheritance; encapsulation d) polymorphism; abstraction
Answer: (d)
55. : d example of a method that is shared by all instance
o aclass. eine 209 P [MODEL QUESTION]
a) Constructor b) Attribute
¢) Constructor and attribute d) None of these
Answer: (b)
56. An inline function is a function that is _[MODEL QUESTION]
a) declared within the class b) expanded in line with the declaration
¢) defined within the class ) equated to zero has no definition
Answi is: (b)
Short Answer Ty} estions
1. What is friend function? [MODEL QUESTION}
Answer:
As per the concept, when a data is declared as private inside a class, then it is not
accessible from outside the class. A function that is not a member or an extemal class.
will ‘not be able to access the private data. A’ programmer may havea situation where he
or she would need to access private data from non-member functions and external
classes. For handling such cases, the concept of Friend functions is a useful tool.
A friend function is used for accessing the non-public members of a class. A class can
allow non-member functions and other classes to access
them friends. Thus,
class.
A friend function of a class is defined outside that
access all private and protected members of the cl
friend functions appear in the class definition, friend:
can bea function, function template, or member function, or a class or class template, in
which case the entire class and all of its members
i n are friends,
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows:
class Box
4
its own private data, by making
a friend function is an ordinary function or a member of another
class’ scope but it has the right to
ass. Even though the. prototypes for
Is are not member functions. A friend
double width;
public:
double length;
friend void printwidth( Box box );
void setWidth( double wid ); :
hs
OOP-18OBIECT-ORIENTED PROGRAMMING
IssTWo as friends of 1 a
8 of élass ClassOne not “as ClassOne, place
To declare all member functions of class Cla
jaliowing declaration in the definiti :
friend class Classtwo
consider the following program:
#include
using namespace std;
class Box
{
double width;
public:
friend void printwidth( Box box );
void setWidth( double wid ); A
Me :
// Member function definition
void Box fetWidth( double wid )
(
width = wid;
}
// Note: printWidth() is not a member function of any
class.
void printWidth( Box box, }
{
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <
#include
using namespace std;
+ class Test
{
public:
Gest(string const gname);
// constructor’ with an argument
-Test(); //destructors
de
Test: :Test (string const: &name)
{
cout << "Test object " << name << " created"
<< endl;
}
Test globaltest ("global");
void func()
{ .
Test functest("func");
) fe
int main()
{ .
Test first("main first");
fune () ;
Test second("main second");
return 0;
J
Generated output:
Test object global created
Test object main first created
Test object func created
Test object main second created
OOP-22BJECT-ORIENTED PROGRAMMING
gt opject main second destroyea
ae object func destroyed
on object main first destroyed
Rest object global destroyed
41. What are the advantages of using ‘new’ operator over malloc 0?
[MODEL QUESTION]
Answer? 3
Operator new constructs an object (calls constructor of object), malloc does not.
Operator new is an operator, malloc is a function.
Operator new can be overloaded, malloc cannot be overloaded.
Operator new throws an exception if there is not enough memory, malloc returns a
NULL.
5. Operator new[] requires to specify the number of objects to allocate, malloc requires
to specify the total number of bytes to allocate.
6 malloc() returns void *, which has to be explicitly cast to the desired type but new
returns the proper type.
7, Operator new/new/] must be matched with operator defete/delete[] to, deallocate
memory, matloc() must be matched with free() to deallocate memory.
42. a) What is a parameterized constructor?
t) Is it mandatory to use constructors in a class? [MODEL QUESTION]
Answer:
a) CH allows constructors to be defined with or without argument lists. Constructor with
parameters is called parameterized constructor. The arguments are supplied when an
object is created.
For the class Person a constructor expecting three strings and an size_t may be handy:
these arguments then represent, respectively, the person's name, address, phone number
and weight. Such a constructor is: ;
Person: :Person(string const &name, string const
&address, string const &phone, size_t weight)
{
dname = name;
d_address = address;
d_phone = phone;
, Giweight = weight;
in a class because default constructors are
ni /
is not ma nstructors ecte
mandatory tg use con declared explicitly in a program, But, some
a i
jilomatically called when no constructor is
es default constructor is not sufficient for all purposes.POPULAR PUBLICATIONS .
Answer:
A copy constructor is a special constructor in the C++ programming language for
creating a new object as a copy of an existing object. The first argument of such a
constructor is a reference to an object of the same type as is being constructed, which
might be followed by parameters of any type.
Normally the compiler automatically creates a copy constructor for each class but for
special cases the programmer creates the copy constructor, known as a user-defined copy
constructor. In such cases, the compiler does not create one. Hence, there is always one
copy constructor that is either defined by the user or by the system.
Copying of objects is achieved by the use of @ copy constructor and an assignment
operator. A copy constructor has as its first parameter a (possibly const or volatile)
reference to its own class type. It can have more arguments, but the rest must have default
values associated with them. The following would be valid copy constructors for class X
Example: ;
X (const X& copy_from_me) ;
Object B = A; // translates as Objec!
(invoke copy constructor)
Object (const Object&)
14. “Use of friend and encapsulation are contradictory” — comment critically.
[MODEL QUESTION)
Answer:
A friend function is tsed for accessing the non-public members of a class. A class can
allow non-member functions and other classes to access its own private data, by making
them friends. Thus, a friend function is an ordinary function or a member of another,
class. e :
There is contradiction between this two because, The encapsulation comes about by
hiding the details of how the class is implemented; you define a public interface
separately from a private implementation. A friend function is used for accessing the non-
public members of a class. A class can allow non-member functions and other classes (0
access its own private data; by making them friends.
15. Differentiate the following:
a) free () and delete
b) friend function and static member function. [MODEL QUESTION]
Answer:
(a) free () and delete _
Free Delete
T. Deallocate space in memory. A block oifl. In the C+* programming language.
memory previously allocated using a call toldelete operator calls the destructor of Us
malloc, calloc or realloc is deallocated, making it}given argument, and returns memory allocate
lavailable again for further allocations, by’ new back to the heap. A call to delete
woid a
Imust be made for every call to new t0 ave"
memory leak.
OOP-24
|OBJECT-ORIENTED PROGRAMMING
Free :
Syntax! ; Delete
Poa free ( void’ * ptr, 2. Syntax:
Delete OBJECT NAME
13, PARAMETERS: Polater toa memory block|3+ Arrays, allocated with new{], must be|
previously allocated with malloc, calloc or|deallocated with delete J, since the layout
irealloc to be deallocated|of — array i i
sary ted ys, allocated with new] — is|
{fa null pointer is passed as argument, no action|implementation defined, and possibly not]
occurs. compatible with new.
(b) Friend Function:
‘As per the concept, when a data is declared as private inside a class, then it is not
accessible from outside the class. A function that is not a member or an external class
will not be able to access the private data. A programmer may have a situation where he
or she would need to access private data from non-member functions and external
classes. For handling such cases, the concept of Friend functions is a useful tool.
A friend function is used for accessing the non-public members of a class. A class can
allow non-member functions and other classes to access its own private data, by making
them friends. Thus, a friend function is an ordinary function or a member of another
class.
A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions. A friend
can be a function, function template, or member function, or a class or class template, in
which case the entire class and all of its members are friends,
Where,
Static Member Function: aie
Static member functions have a class scope and they do not have access to the ‘this’
pointer of the class. When a member is declared as static, @ static member of class, it has
only one data for the entire class even though there are many Objects created for the class.
The main usage of static function is when the programmer wants fo have jafunction
Which is accessible even when the clas isnot instantiated.
General syntax:
Static return_data_type
/static function defined
fuentionname () -
with keyword static
Statement1; ic functi
i 6 dyed ¢ function
//Statements for execution inside stati
Statement2;
OOP-25POPULAS
IBLICATIONS
Accessing Static Function:
‘A normal member function is accessed using the -object and an operator called the dot
member access operator. The functions declared static or static functions are accessed
using only the class name and the scope resolution operator, unlike in normal member
fimetions where these are not used.
46. Write a program to return an object using ‘this’ pointer. [MODEL QUESTION]
Answer:
extern Person *const this;
A member function like name(), which returns the namie field of a Person, could therefore
be implemented in two ways: with or without the this pointer:
class Person
{
public: // extension of the class Person
char 4_name; // earlier members are assumed.
char const name() ; .
yi .
char const *Person::name() //implicit usage of ‘this’
{
return 4_name;
char const *Person::name()//explicit usage of ‘this’
OO abla’ ene si jntnay
void maint )
‘ Person pl , p2
Pl.name();
P2.name();
cout << *pl=" << pl;
cout << “pl=" << pl;
i
17. Explain “Encapsulation” and “Data Abstraction” in the context of Object
Oriented Programming witha focus on their need. [MODEL QUESTION]
Answer:
Data Abstraction:
In data abstraction, access to the data is provided through a specific set of operations
defined to examine and manipulate the data, For instance, when a programmer is using
C++ standard data types, this means that users are using the concept of data abstraction,
When using data types, the users are not concerned with how the data is stored but they
are concerned with what operations are provided and what properties are supported.
Data Encapsulation:
Encapsulation is the process of combining data and functions into a single unit called
class. Using the method of encapsulation, the programmer cannot directly access the data.
OOP-26Data is only accessible through the functions present inside the class. Data encapsulation
led to the important concept of data hiding. Data hiding is the implementation details of a
class that are hidden from the user.
For instance: -
class Example
(
public:
int sample();
int example(char *se)
int endfunc();
Other member functions
private:
int x;
float sa;
. HOther data members
In the above example, the data members integer x, float sq and other data members and
member functions sample(),example(char* se),endfunc() and other member functions are
bundled and put inside a single autonomous éntity called class Example.
18. What is static function? Write a small program to illustrate the same.
[MODEL QUESTION]
Answer:
Static member functions:
Static Member Function: :
Static member functions have a class scope and. they do not have access to the ‘this’
pointer of the class. When a member is declared as static, a static member of class, it has
only one data for the entire class even though there are many objects created for the class.
The main usage of static function is when the programmer wants to have a function
which is accessible even when the class is not instantiated.
#include
class Test
{
private:
static int x;
public:
static int count()
{
return x;
}
di
int Test oF
OOoP-27PUBI IS
int main()
{
printf_s("td\n", Test::count());
return 0;
d
in inline and outline member functions of a class.
19, Suggest an example to explai MODE! GuESTOny
Answer:
An inline function is a new feature of C++. An inline function is a function that is
expanded in’ line when it is invoked, ie., compiler replaces the function call with the
corresponding function code. The inline functions are defined as follows:
inline function_header if
t ib
function body
)
For example, we can define an inline function to compute th¢ square of an integer
variable in the following way: |
inline int square(int x)
{
return(x * x);
}
Now this function can be called in the following ways:
A = square (12);
B = square(6+3);
On the execution of these statements, the values of A & B will be 144 & 81 respectively.
So, in the second calling it will send 9 to the function,
Now, the advantages, disadvantages and restrictions of inline functions over normal
functions are given below:
Inline expansion makes a program faster because the overhead of a normal function call
and return is eliminated. However, it makes the program to take more memory because
the statements that define the inline function are reproduced at each point where the
function is called. The speed benefits of inline functions diminish as the function grows
in size. At some point the overhead of the function call becomes small compared to the
execution of the function, and the benefits of inline functions may be lost. In stich cases,
the use of normal functions will be more meaningful. Inline keyword sends a request to
the compiler (not a command). The compiler may ignore this request if the function
definition is too long or too complicated and compile the function.as anormal function.
In the following situations, inline expansion may not work:
* For functions returning values, if'a loop, a switch, ot a goto exists.
* For functions not returning values, if'a return statement exists
* If function contains static variables
* Ifinline functions are recursive
Inline functions are different from macros in the following ways:
OOP-28OBJECT-ORIENTED PROGRAMMING
Macros are Preprocessor directives & are processed before compilation starts. The
gefinition starts with the symbol “#, which is preprocessor directive, Incase of inline
functions, the definition starts with the keyword ‘inline’, The expansions of those
functions are done by the compiler. Another important difference is that. whether inline
expansion will occur or not, that’s fully compiler’s decision, That means sometimes the
inline functions may be treated like a-normal function, But this is not the case with
mmaer0s. a
Finally, in case of inline functions, there is no blind substitution of actual arguments,
which may be the case for macros. For example, consider the following calling statement:
X = square(6+3);
‘Now, if square() is a macro with argument, the result of X is 27. But, if the square is an
inline function, we’ll get the result as 81.
20. Justify or falsify - “Declaration of a constructor must be accompanied by that
of a destructor”. [MODEL QUESTION]
Answer:
Not necessarily.
A destructor is the reverse of a constructor. It is called when an instance of a class is
destroyed, e.g. when an object of a class created in a block (set of curly braces "{}") is
deleted after the closing brace, then the destructor is called automatically. It will be called
upon emptying of the memory location storing the variable. Destructors can be used to
release resources, such as heap-allocated memory and opened files when an instance of
that class is destroyed.
If not declared by user it's available in a class by default but it now can only deallocate
memory from the objects of a class when an object is deleted.
21. What is containership? How does it differ from inheritance?
" e [MODEL QUESTION]
Answer:
I" Part:
Manipulators are operators used in C++ for fo
the programmer's choice of display.
There are numerous manipulators availa
Manipulators are: endl, setw, setfill, ete. 5 ale ond
When a class contains objects of another class or its members, this kind of relationship is
called containership or nesting and the class which contains objects of another class as its
Members is called as container class. Containership is basically type of hierarchy. It can
also be called containment hierarchy. In other words, possessing of objects of other
Slasses in a class is called containership oF nestInB-
rmatting output. The data is manipulated by
ble in C++. Some of the more commonly used
Part: i
I: ‘ concepts, they are quite different i
Althor 5 jnership are two OOP concepts, they ar rent in
wha He Inheritance and coe to achieve. Inheritance is the ability fora class to inherit
Dropertic, ae us gs parent class By extending It while Containership is the
and behavior
oop-29POPULAR PUBLICATIONS
ability of a class to contain objects of different classes as member data. If a class is
extended, it inherits all the public and protected properties/behavior and those behaviors
may be overridden by the subclass: But if a class is contained in another, the container
does not get the ability to change or add behavior to the contained. Inheritance represents
an “is-a” relationship in OOP, while Containership represents a “has-a” relationship,
22. Why the argument of a copy constructor is passed by reference.
[MODEL QUESTION}
Answer:
A reference variable is just like pointer variable with few differences. It is declared using
“&” operator. A reference variable must always be initialized. The reference variable
once defined to refer to a variable can’t be changed to point to other variable. Array of
references can't be created like the way it is possible with,pointer.
Yes, it's mandatory in case of the copy constructoé to pass the reference of an object. In
copy constructor, we pass the reference of the object which we want to copy on another
object, é.g., copy the content of the object A into B, where we provide the reference of A.
If we try to do the same thing by passing of value, actually we are copying the content of
A into dummy object which will be declared in a constructor as a type (not a reference
one), then compiler copy the dummy object into B, which is really not a efficient way,
and at this point question arise about the life time of the dummy object which hold the
value of A, its destruction and memory management,
23. State the basic differences between a ‘Structure’ in C and a ‘Class’ in C++,
[MODEL QUESTION]
Answer:
C+ Supports all the, features of structures as defined in C. But C++ has expanded its
capabilities further to suit its OOP philosophy. It attempts to bring the user-defined types as
close as possible to the built-in data types, and also provides a facility to-hide the data which
is one of the main precepts of OOP. Inheritance, a mechanism
characteristics from other types, is also supported by C+,
In C++, a structure can have both variables and functions-as members. It can also declare
some of its members as ‘private’ so that they cannot be accessed
functions,
In C++, the structure names are stand-alone and can be used lik
That is, the keyword struet can be omitted in the declaration o
example, we can declare the student variable A as
student A; // C++ declaration
This is an error in C,
C++ incorporates all these extensions in another user-defined type known as elass. There is
very little syntactical difference between structures and classes in C++ and, therefore, they
can be used interchangeably with minor modifications. Since class is a specially introduced
data type in C++, most of the C++ programmers tend to use the structures for holding only
data, and classes to hold both the data and functions,
by which one type can inherit
directly by the external
any other type names
f structure variables. For
OOP-30OBJECT-ORIENTED PROGRAMMING
nthis context one important point to note that wh
to class all these latever the features discussed with respect
features
S are Supported by the structure of C++ but not the traditional C.
24, a) Should one constructor call another Constructor as a primitive?
[MODEL QUESTION]
Answer? Ne
No. Even though it is possible, it will not do what the programmer thinks it is doing,
b) When a copy constructor should be defined?
Answer:
A user-defined copy constructor is generally needed when an object owns pointers or
non-shareable references, such as to a file, in which case a destructor and an assignment
operator should also be written,
25. Write a function in C++ to search for details (Phoneno and Calls) of those
Phones which have more than 800 calls from binary file “‘phones.dat”. Assuming
that this binary file contains records/objects of class Phone, which is defined
below:
class Phone
t
Char Phoneno[10]; int Calls;
Public: :
void Get( ) {gets(Phoneno); cin>>Calls;}
void Billing ( ) (cout<800)
PBilling();
yyrcleseQ) i //ignore
estions
Long Answer Type
7 j jon and macro. ie
4; a pistinguish between inline et Can a constructor be virtual? Justify your
i lat is the use of virtual de: [MODEL QUESTION}
er.
oopP-3tPOPULAR PUBLICATIONS
Answer: .
a) Inline functions are different from macros in the following ways:
Macros are preprocessor directives & are processed before compilation Starts. The
definition starts with the symbol ‘#’, which is preprocessor directive. Incase of inline
functions, the definition starts with the keyword ‘inline’. The expansions of those
functions are.done by the compiler. Another important difference is that, whether inline
expansion will occur or not, that’s fully compiler’s decision. That means sometimes the
inline functions may be treated like a normal function. But this is not the case with
macros. .
Finally, in case of inline functions, there is no blind substitution of actual arguments,
which may be the case for macros. For example, consider the following calling statement
X = square(6+3);
Now, if square() is a macro with argument, the result of X is 27. But, if the square is an
inline function, we'll get the result as 81.
b) Refer to Question No. 9 of Short Answer Type Questions.
2. a) Differentiate the following: [MODEL QUESTION)
i) Malloc() and new
ii) Friend and member function
Answer:
i) Refer to Question No. 11 of Short Answer Type Questions.
ii) Friend Function: Refer to Question No. 1 of Short Answer Type Questions.
Member Function:
Member functions are operators and functions that are declared as members of a class.
Member functions do not include operators and functions declared with the friend
specifier. These are called friends of a class. You can declare a member function as static;
this is called a static member function. A member function that is not declared as static is
called a nonstatic member function.
The definition of a member function is within the scope of its enclosing class. The body
of a member function is analyzed after the class declaration so that members of that class
can be used in the member function body, even if the member function definition appears
before the declaration of that member in the class member list. When the function add() is
called in the following example, the data variables a, b, and ¢ can be used in the body of
add().
class x
{
public:
int. ada()
(return atbtc;)};
private:
int a,b,c;
// inline member function add
Ve
OOP-32OBJECT-ORIENTED PROGRAMMING
p) What is constructor? Explain different types of constructor with example.
STIO!
Answer? [MODEL QUE: IN]
Constructor is used for Initializing'the values to the data members of the Class.
1) Constructor is that whose name is same as name of class.
2) Constructor gets Automatically called when an object of class is created.
3) Constructors never have a Return Type even void.
4) Constructor are of Default, Parameterized and Copy Constructors.
The various types of Constructor are as follows:
1, Default Constructor: Default Constructor is also called as Empty Constructor which has
‘no arguments and It is Automatically called when we creates the object of class but name
of Constructor is same as name of class and Constructor never declared with the help of
Return Type. Means we cant Declare a Constructor with the help of void Return Type, if we
never Pass or Declare any Arguments then this called as the Copy Constructors.
Example :
class Cube
(
int side;
public:
Cube ()
{
side=10;
}
ve
int main()
{
Cube c;
cout << c.side;
}
Output: 10 A Bap cinta ats
In this case, as soon as the object is created the constructor ts called.which initializes its
data members.
2. Parameterized Constructor: This is Another type Constructor which has some
Arguments and same name as class name but it uses some Arguments = For this We
have to create object of Class by passing some Arguments a e bgehe a hen itae mies
with the name of class, When we pass some Arguments to the onstucte then this will
automatically pass the Arguments to the Constructor and the values will retrieve by the
Respective Data Members of the Class.
xample :
ase Cube
int side;
Public; ooP-33POPULAR PUBLICATIONS
Cube (int x)
{
side=:
}
vi
int main()
{
Cube 1 (10);
Cube 2 (20);
Cube 3 (30);
cout << cl.side;
cout << c2.side;
cout << c3.side;
d
OUTPUT : 10 20 30
By usisg parameterized construcor in above case, we have initialized 3 objects with user
defined values. We can have any number of parameters in a constructor.
3. Copy Constructor: This is also Another type of Constructor, In this Constructor we
pass the object of class into the Another Object of Same Class. As name Suggests you
Copy, means Copy the values of one Object into the another Object of Class .This is used
for Copying the values of class object into-an another object of class So we call them as
Copy Constructor and For Copying the values We have to pass the name of object whose
values we wants'to Copying and When we are using or passing an Object to a
Constructor then we must have to use the & Ampersand or Address Operator.
Copy Constructor is a type of constructor which is used to create a copy of an already
existing object of a class type. It is usually of the form X (X&), where X is the class
name.he compiler provides a default Copy Constructor to all the classes.
Syntax of Copy Constructor
class-name (class-name &)
(
)
As it is used to create an object, hence it is called a constructor. And, it creates a new
object, which is exact copy of the existing copy, hence it is called copy constructor.
c) What is the advantage of user-defined copy constructor ‘over default copy
constructor? [MODEL QUESTION)
Answer:
For copy constructor
Refer to Question No. 13 of Short Answer Type Questions.
A copy constructor is called when a new variable is created from an object. The default
copy constructor does a shallow copy i.e.; the copied object points to same old memory
pointed by the parent object. If the object has some dynamic memory or pointers, it is
OOP-34create a COPY Construct
ser to real for. When a ne . .
ent and destructor also should be wweltten ince is written, assignment
Tribe programmer is defining the Copy constructor, the compiler will invoke th:
sanstraetor at the time of copying the members of the calling object to the crembers of
the called object This will Creates the problems if the sheet con ins ‘the | inte
variables. The time copying 1S More if there are more number Gh bj non oe
The default copy constructor is generated by the compiler when the aes rot
Explain the following type conversions with sui :
aor hesio to user-defined ith suitable examples:
ji) From user — defined to basic
ii) Conversion between objects of two different classes. [MODEL QUESTION]
‘Answer?
Basic to Class type
The conversion from basic type to class type is easy to accomplish. Let us consider a
constructor to build a string type object from a char* type array.
string .:: string (char *a)
(
length = strlen(a);
p= new char{length + 1];
stropy(D, a);
}
this constructor builds a string’ type object from a char* type variable. a. the variables”
length and p are data members of the class string. Once this constructor has been defined
in the string class, it can be used for conversion from char* type to string type. For
example, let us consider the following code:
string sl, s2;
char *namel = “abcd!
char *name2 = “xyzw";
81 = string(namel);
s2 = name2;
the statement
$1 = string(namel) j
first converts namel from chai
tothe object s1.
The statement
i & sans ;
Also do the same job by invoking the constructor imp
r* type to string type and then assigns the string type values
licitly.
Class to Basic type
7 order to do the opposite thing
nar that could be used to convert §
Sverloaded casting operator function 4
low:
we have to use the concept of overloaded casting
ta class type data to basic type. The general form of
Igo known as conversion funetion, is shown
bel
ooP-35POPULAR PUBLICATIONS
operator typename ()
{
}
The function converts a class type data to typename. For example, the operator double()
converts a class object to type double, the operator int() converts a class type object to
type int, and so on.
Let us consider the following example:
vector :: vector double()
{
double sum = 0;
for (int I = 0; I
mespace std;
that are used so infrequently that a default value
wlt-argument facility
'y allows for specifying only
are meaningful in a given call
"function parameters, For example:
prae-
je flint a) ( return a; )
pe gant X= £(a)) { return x; }
int nh) ¢
az 2i
int.a = 3;
return g();
}
gat main() (
cout << h() << endl;
This example prints 2 to standard output, because the a referred to in the declaration of
(isthe one at file scope, which has the value 2 when g() is called.
‘The default argument must be implicitly convertible to the parameter type.
A pointer to a function must have the same type as the function. Attempts to take the
address of a function by reference without specifying the type of the function will
produce an error. The type of a function is not affected by arguments with default values.
b) Inline Function:
When a function is defined inside a class, it is treated as an inline function.
Defining members inline has the following effect: Whenever an inline function is called
ina program statement, the compiler may insert the function's body at the location of the
function call. The function itself may never actually be called. Consequently, the function
call is prevented, but the function's body appears as often in the final program as the
inline function is actually called. This construction, where the function code itself is
inserted rather than a call to the function, is called an inline function.
Using inline functions may result in multiple occurrences of the code of those functions
ina program: one copy for each invocation of the inline function. This is probably OK if
the function is a small one, and needs to be executed fast. It's not so desirable if the code
ofthe function is extensive. The compiler knows this too, and considers the use of inline
inctions a request rather than a command: if the compiler comicers the function too
ne. it will not grant the request, but will, instead, teat the function as @ normal
ion,
a Class and an Object? Justify if it is possible to
6 ity
hatihat is the relation between [MODEL QUESTION}
Ve an object of more than one distinct classes.
ooP-37POPULAR PUBLICATIONS
Answer:
> A cclass is a definition of an object. It's a type just like int. A class resembles a struct
with just one difference : all struct members are public by default. All classes
members are private.
> Aclass is a type, and an object of this class is just a variable.
A class contains the descriptions of all the behaviors of the objects that it represents.
In addition, a class may, but not always, contain descriptions of the internal data held
_ by the objects, called its fields, as well as implementation details about its methods
and fields.
Yes, it's possible to have one object of more than one classes. This festure is called
multiple inheritance. At first a.class must be constructed from more than one class then
from that class the object can be declared.
v
6. a) What is constructor? Explain the constructor overloading with an example.
b) What is garbage collection? What do you mean by automatic garbage
collection? Whether C++ support automatic garbage collection or not?
[MODEL QUESTION]
Answer:
a) 1" Pai
Constructor is used for Initializing the values to the data members of the Class.
1). Constructor is that whose name is same as name of class.
2) Constructor gets Automatically called when an object of class is created.
3) Constructors never have a Return Type even void.
4) Constructor are of Default, Parameterized and Copy Constructors.
Features: Refer to Question No. 4 of Short Answer Type Questions.
2" Part:
Constructor overloading process is very similar to the overloading of other functions.
Since constructors are also functions, they can be overloaded like any other functions.
This allows user to create many constructors, which can help user to create (and set)
objects differently. Different constructor can allow creation of objects with desired type
of values.
#include
#¥include
elass ol 7
{
public:
o1()
(
cout<<*Hello"<
#include
class time24
{
int hours, minutes, seconds;
public:
time24()
{
hours=minutes=seconds
}
time24(int h,int m,int s)
hours=|
Rinutes
Seconds=s;
a display ()
4£(hours<10)
Cout<<'9";
Sout<>ht;
if (hl>23)
return (1);
cout<<"Minutes:";
cinpoml;
cout<<"Seconds
cin>>s1;
time24 t24(h1,m1,s1);
cout<<"you entered: ";
t24.display ();
cout<
aes: sample
int a, b;
Public:
Sample(int x, int y)i
Void operator ++();
Void operator ++(int x) 7
yoi4 display();
int y)
Sample ;
oopP-4l
sample’ (int x,POPULAR PUBLICATIONS
void sample
(
ate;
b++;
)
void sample :: operator ++(int x)
{
a t+;
bet;
)
void sample :: display()
‘
cout << “a i" << @ <<"b:” << b;
) .
int main()
{
sample z(10, 20);
cout << “before overloading";
z.display();
442;
cout <<*after overloading-prefix form";
z.display();
zt:
cout <<*after overloading-postfix form’;
z2.display();
return 0;
}
operator ++()
9. Define a class in C** with following description: [MODEL QUESTION]
Private Members
* Adatamember — Flight number of type integer
Adatamember _ Destination of type string
Adatamember Distance of type float
Adatamember Fuel of type float
A member function CALFUEL/() to calculate the value of Fuel as per the
following criteri:
Distance Fuel
<=1000 500
more than 1000 and <=2000 1100
More than 2000 2200
Public Members
“A function FEEDINFO() to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
“~ function SHOWINFO() to allow user to view the content of all the data members.
OOP-42)BJECT-ORIENTED PROGRAMMING
‘Answer: i
4 include
4 include
4 include
class FLIGHT
, Int Fno;
char Destination [20];
float Distance, Fuel;
void CALFUEL();
public:
void FEEDINFO();
void SHOWINFO();
u
void FLIGHT: :CALFUEL();
{
If (Distance < 1000)
Fuel = 500;
else
If (Distance < 2000)
Fuel = 1100;
else
Fuel = 2200;
)
void FLIGHT: : FEEDINFO()
{
cout << “Flight No:";
cin >> Fno;
cout << “Destination:
gets (Destination);
cout <<* “Distance
cin >> Distance;
CALFUEL () ;
)
void FLIGHT: :SHOWINFO()
(
cout << “Flight No. ¢ “<
#include
class student
t
protected:
int entryno;
char name(20];
public:
void getdata()
t
cout<<"enter name of the student"<>name;
)
void display()
t
cout<<"Name of the student is"<>pem[j];
)
)
void display()
{
entryno=1;
cout<<"entry no for Science student is*<>ehe [5];
}
3
void display ()
{
entryno=2;
cout<<"entry no for Arts student is*<
class Student
{
protected:
char *name;
char roll;
char marks;
char *year;
Student class has the following attributes: Name
marks and year (character type pointer)
ing the constructor (use the constructor overloading)
‘cords and print the student name and roll number who
OOP-46BIECT-ORIE! (OGRAMMING.
publ eudent ()
Student + Name
{ (NULL), 011 (-1), marks (0), year (NULL)
}
student (char *n, int r, int m char ty)
; os
setName (n) ;
setRoll (x);
setMarks(m) ;
setYear(y) ;
}
student (Student &s)
{
name = s.getName();
roll = s.getRoll(); *
> marks = s.getMarks();
year = s.getYear();
)
void setName(char’ *n)
{ .
name = new char[strlea(n) + 1];
strepy(name, n);
)
void setRoll(int r) { roll = x; }
void setMarks(int m) ( marks = m; }
void setYear(char *y)
£
year = new char{strlen(y) + 11;
strepy(year, y)i
}
char *getName() { return name; }
int getRoll() { return roll; }
int getMarks() ( return marks; }
char *getYear() { return year; }
Student operator =(const Student &s)
{
name = s.getName();,
roll = s.getRollt);
marks = s.getMarks();
year = s.getYear();
return *this;
}
di
int main()
{
Student students[5];
students[0] = student ("MercUury” » tReet
students [1] “= Student (*Venue", 2. 68) "Ctyo ee
students(2] = Student ("Jupiter", 4, 9% g
OoP-47POPULAR PUBLICATIONS
students [3]
students [4]
int maxMarks
for (int i =
{
student ("Saturn", 5, 76, "1955");
student ("Uranus", 11, 46, "1922");
=1, index = -1;
L.< 5y-de+)
if (students[i).getMarks() > maxMarks)
c ‘
° maxMarks = students({i].getMarks();
index = it
)
std::cout << "Student scoring highest is " <<
students [index] .getName()
<< " whose roll number is " <<
students [index] .getRoll()
13. Write a class to represent com| numbers with necessary constructors.
Overload “ “” operators using friend function. A complex number is of the
form a + ib where a and b are real numbers. Two complex numbers a + ib and c + id
are added to obtain the sum: (a + c) + i(b + d). Two complex numbers are multiplied
to obtain the product (ac - bd) + i(bc + ad). Also write a main function to
demonstrate all operations involved complex numbers. [MODEL QUESTION]
Answer:
#include
#include
#include
struct complex
{
float rel;
float img;
}s1,82;
void main()
{
clrser();
float a,b;
cout<<"Enter real and ima
cin>>s1.rel>>s1.img;
cout<<"Enter real and ima
cin>>s2.rel>>s2.im
//RAdi tion
a=(s1.rel)+(s2.re1) ;
b=(s1.img) +(s2.img) ;
cout<<*nAddi tion:
//Subtraction
a=(s1.rel)~(s2.rel);
ginary part of 1st complex number:";
ginary part of 2nd complex number;
SST (Ses ace*) Meet aecet (Neebect) Hee"?
OOP-48BJECT-ORIEN’ \GRAMMING
pe (s.img) - (82. img) ;
out<<™nSubtraction: *<<"(ccacen) #cenye
ee altiplication (S
using namespace std;
class employee
$
int emp_num;
char emp_name(20);
float emp_basic;
float sal;
float emp_da;
float
float
publi
void get_details();
void find_net_sal()i
void show_emp_details();
di
void employee :: get_details()
{ .
cout<<"\nEnter employee number: \n";
cin>>emp_num; ant,
cout<<"\nEnter employee name: \n";
cin>>emp_name; siti
cout<<"\nEnter employee basic:\n";
cin>>emp_basic;
)
void employee +:
{
emp_da=0 .52*emp_basic? :
emp_it=0.30* (emp_basicremp_da) te
‘emp_basic+emp_da) ~emP—
find_net_sal ()
oop-49POPULAR PUBLICATIONS
void employee
{ i
cout<<"\n\n\nDetails of +
cout<<*\n\nEmployee number:
cout<<*\nBasic salary :
cout<<"\nEmployee DA
cout<<"\nIncome Tax :
cout<<"\nNet Salary :
)
int main()
€
employee emp(10];
int i,numj
show_emp_details()
*<>num;
for (i=0; i .
class M
{
protected:
int m;
public:
void gét_m(int);
Vi
class N
{
protected:
int n;
public:
void get_n(int);
class P: public M, public'N
public:
void display (void) ;
i
void M::get_m(int x)
{
m=x;
}
void n::get_n(int y)
ney;
)
void P::
{
Cout<<*"m="<( 1 ) // works -- call to explicit
constructor via explicit cast. : ;
bar( foo( 1.0) ); // works -- explicit call to explicit
constructor
// with automatic conversion from float to int.
4) Mutable:
C+, however, allows the construction of objects which are, in a sense, neither const
objects, nor non-const objects. Data members, which are defined using the keyword
mutable, can be modified by const member functions.
‘An example of a situation where mutable might come in handy is where a const
object needs to register the number of times it was used. The following example
illustrates this situation:
#include
#include
#include
class Mutable
{
std::string dname;
mutable int d_count; // uses matable keyword
public:
Mutable (std::string const gname)
d_name (name) ,
4_count (0)
Q 4
void called() const
(
std::cout << "Calling * << dname <<
"(attempt " << +#@_count << ")\n";
)
de
int main()
t
Mutable const ("Constant mutable object");
for (int idx = 0; idx < 4; idxt+)
; x.called(); // modify data of const object
Generated output:
Calling Constant mutable object (attempt 1)etc.
The keyword mutable may also be useful in classes implementing, e.g., reference
counting.
€) Static_cast Operator:
OOP-s4QBIECT-ORIENTED PROGRAMMING
static.
explicitly document a cast that woul
following example:
rue;
tatic_cast (b);
4+ automatically casts bool to int in thi oe -
mn necessary. However, by using it, no Context so the use of static_cast in this case
‘ogrammers document their intention explicitly.
in other contexts, static_cast is mand; ven -$ou cast Cold
9 1 : ndatory. For example, when you cast void* to a
different pointer type, as in the following example:
int n=4;
void *py=8ns :
int *pi2 = static_cast (pv); /Imandatory
static_cast uses the information available at compile time to perform the required type
conversion. Therefore, the target and the source might not be identical in their binary
representation. Consider a float to int conversion. The binary representation of the
floating number 10.0 is quite different from the equivalent integer value of 10. static_cast
performs the necessary adjustments when casting one to the other.
The use of static_cast enables the compiler to catch programmers’ mistakes such as this:
const char *msg="don't touch
unsigned char *p=
static_cast (msg); //error
Here the compiler issues an error message indicating that the cast operation attempts to
remove the const qualifier. of msg -- something that the programmer probably” didn't
intend anyway.
‘The static_cast operator converts a given expression to a specified type.
static_cast operator syntax
-static_cast--<--Type-->+
-expression--)
The following is an example of the static_cast operator.
finclude
Using namespace std;
int main() {
int j = 41;
int v
float m= 3/v; ‘
float d = static_cast(3)/Vi
cout << m=" << m << endl;
cout <<" = " ee a << endl;
)
The following is the output of the above example:
m= 10
10.25
In this example, m = j/v; produces an an
‘Onversely, d = static_cast(j)/Vi
swer of type int because both j and v are integers.
produces an answer of type float, The static_cast
oop-55POPUL |LICATIONS
operator converts variable j to a type float. This allows the compiler to generate a division
with an answer of type float, All static_cast operators resolve at compile time and do not
remove any const or volatile modifiers. ; | :
Applying the static_cast operator to a null pointer will convert it to a null pointer value of
the target type. : :
You can explicitly convert a pointer of a type A to.a pointer of a type B if A is a base
class of B. If A is not a base class of B, a compiler error will result,
You may cast an Ivalue of a type-A to a type B& if the following are true:
* Aisa base class of B
* You are able to convert a pointer of type A to a pointer of type B
+ The type B has the same or greater const or volatile qualifiers than type A
* Ais nota virtual base class of B
The result is an Ivalue of type B.
A pointer to member type can be explicitly converted into a different pointer to member
type if both types are pointers to members of the same.class. This form of explicit
conversion may also take place if the pointer to member types are from separate classes,
however one of the class types must be derived from the other.
f) Static class and member:
We can have static class in java. In java, we have static instance variables as well as static
methods and also static block. Classes can also be made static in Java. Java allows us to
define a class within another class. Such a class is called a nested class. The class which
enclosed nested class is known as Outer class, In java, we can’t make Top level class
static. Only nested classes can be static.
A data member of a class can be qualified as static. The speci:
variables are given below:
* It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
* Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
* Its visible only within the class, but its lifetime is the entire program.
‘Static variables are normally used to maintain values common to the entire class.
features of static member
Static member functions are required for the following reasons:
* A static function can have access to only other static members(members or variables)
declared in the same class,
«A static member function can be called using the class name (instead of its objects) as
follows:
class_name :: function_name;
The following program illustrates the concept of static data members and static member
functions:
#include
class xyz
{
int n;
OOP-56OBJECT-ORIENTED PROGRAMMING
static int count;
ie:
pop jid setval ()
te
n = ++ count;
)
void show_n()
(
cout << “value of ni" << n cer\n";
)
static void showcount (voia)
(
cout << ‘value of count:" << count <<"\n";
)
hi
int xyz
int main()
i
xyz a, bi
a.setval ();
b.setval () ;
xyz :: showcount();
vest ¢:
c.setval ();
xyz 1: showcount ();
a.show_n():
b.show_n();
c-show_n() ;
return 0;
)
count;
oopP-57POPULAR PUBLICATIONS
OPERATOR OVERLOADING
1, For overloaded function, the compiler chooses the right specific version on the
basis of the parameter is [MODEL QUESTION}
a) Type b) Order c) Number d) All of these
Answer: (d)
2. Which of the following operators may be overloaded? [MODEL QUESTION]
a) : (Member) b) :: (Scope resolution)
¢) % (Modulus) d) 2: (Conditional)
Answer: (c)
3. Which operator of the following cannot be overloaded? [MODEL QUESTION]
a) b) ?: ot d) delete
Answer: (b)
4. In binary. operator overloading how many arguments does a member function
take? [MODEL QUESTION}
a) One b) Two ©) Three d) Four
Answer: (a)
5. Which operator of the following cannot be overloaded? [MODEL QUESTION]
a): b)T] > 3
Answer: (c)
6. Which of the following operators cannot be overloaded?’ [MODEL QUESTION]
a) Scope resolution operator b) Arrow operator
c) Equality operator ) Assignment operator
Answer: (a)
7. Which of the following correctly describes overloading of functions?
[MODEL QUESTION]
b) Ad-hoc polymorphism
4) Transient polymorphism
a) Virtual polymorphism
c) Pseudo polymorphism
Answer: (a)
8. Operator functions (MODEL QUESTION]
a) can return a value b) cannot return a value
c) may return values of limited data types d) none of these
Answer: (a)
9. Which operator cannot be overloaded in C++? [MODEL QUESTION]
a). b) i: ¢)Bothaandb ——d) None of these
Answert (c) .
OOP-58OBJECT-ORIENTED PROGRAMMING
0. Which operator is having the highest
‘ a) Postfix b) Unary ighest precedence?
Answer? (a)
[MODEL QUESTION]
¢) Shift d) Equality
Short Answer Juestions
4,Why destructor cannot be overloaded?
Answer?
No.
You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It
never takes any parameters, and it never returns anything. You can't pass parameters to
the destructor anyway, since you never explicitly call a destructor.
[MODEL QUESTION]
2, Distinguish between static casting and dynamic casting? [MODEL QUESTION]
Answer:
In general static_cast is used when you want to convert numeric data types such as
enums to ints or ints to floats, and you are certain of the data types involved in the
conversion.
static_cast conversions are not as safe as dynamic_cast conversions, because static_cast
does no run-time type check, while dynamic_cast does. A dynamic_cast to an ambiguous
pointer will fail, while a static cast returns as if nothing were wrong; this can be
dangerous. Although dynamic_cast conversions are safer, dynamic_cast only works on
pointers or references, and the run-time type check is an overhead,
class B {};
class D : public B (};
void £(B* pb, D* pd) (
D* pd2 = static_cast(pb); // not safe, pb may
// point to just B
Bt pb2 = static_cast(pd); // safe conversion
)
In contrast to dynamic_cast, no run-time check is made on the sta
any object. as if :
Consequently, static_east can do the inverse of implicit conversions, in which case the
results are undefined. It is left to the programmer to verify that the results of a static_cast
conversion are safe.
cast conversion of
3. a) What is operator overloading?
Mention omarules for overloading operators. [MODEL QUESTION)
Answer: finiti i
% i definitions (i.e:, some additional tasks)
Operator jing means creating some New ‘i x
for that eee not defined for that operator. Now, to do this, we must specify
What it vane ia lation to the class to which it is applied. A special function, known as
eng, means in.relation specify this new definition The general Form ofthis operator
r function, 15 Us
function is:
Return_type classname +?
operator oP
oopP-59POPULAR PUBLICATIONS
(arg_list)
c
Function body //task defined
)
The process of overloading involves the following steps:
|. Only existing operators can be overloaded. New operators cannot be created.
2. The overloaded operator must have at least one operand that is of user-defined type.
3. Overloading cannot change the basic meaning of an operator.
4. Overloaded operators follow the syntax rules of the original operators. They cannot
be overridden. etc.
b) Write a program to overload + and — operators as unary operator.
- [MODEL QUESTION]
Answer:
class Point
{
private:
double m_dx, mid¥,. m_dz;
public:
Point (double dx=0.0, double dy=0.0, double dz=0.0)
{
m_dX = ax;
may = @
m_dz = di
)
“/ Convert a Point into it's negative equivalent
friend Point operator- (const Point &cPoint) ;
// Convert a Point into it's positive equivalent
friend Point operator+ (const Point &ePoint) ;
double Getx() ( return max; }
double Gety() { return m_dy; }
double Getz() { returnmdz; }
ts
// Convert a Point into it's negative equivalent
Point operator- (const Point &cPoint)
(
return Point (-cPoint.m_Gx, -cPoint.m_d¥, -cPoint mdz);
2
// Convert a Point into it's positive equivalent
Point operator+ (const Point &cPoint)
{
return Point (+cPoint.m 4x, +cPoint.ma¥, +cPoint.m az);
}
void main()
i
Point p1(2.3 , 5.7 ,8.9);
Point p1(2.2 , 1.4 ,8.2);
cout << “-P1"<< -P1;
OOP-60OBI IENTED PI
cout << “#P1"c< 4p1,
)
. ny Program in G +* to overload [] operator, [MODEL QUESTION]
Answer:
ginclude
class sample
{
int a(20];
int size;
public:
sample()
{ .
for(int I = 0; I < 20; I++)
all] =I * 2;
}
int operator[]() (int x)
{
return a(x];
int main()
{
sample a;
for (int I =0 ;I < 20 ; I++)
cout <<*location * << I << “value * << a[]()I;
return 0;
}
5. Write a program to overload >> and << operators to read and dispiay a vector.
[MODEL QUESTION]
Answer:
#include
#include
const size = 3;
class vector
{
int v[size];
Public:
vector () ; ; :
friend istream,& operator >> (istream &,vector &);
friend ostream & operator << {ostream &, vector &);
oe tt vector ()
for(int i=0;i> (istream & din, vector & b)
t
for(int is0;i>b.vli];
return (din) ;
}
ostream & operator << (ostream & dout,vector & b)
t
dout<<" (";//< size)
{
dout<<",";
}
dout<<")";
}
return (dout) ;
}
void main()
{
elrser();
vector m;
cout<<"Enter elements of vector m \n";
cin>>m;
cout<
6. How to overload prefix and postfix operator? [MODEL QUESTION]
Answer:
Refer to Question No. 10(a) of Long Answer Type Questions.
1. a) How can we distinguish between prefix and postfix nature while overloading
the unary +4 operator?
b) Write a program to overload the new operator. [MODEL QUESTION]
OOP-62BJECT-ORIENTED PROGRAMMING
Answel
a) Overloading the increment operator (operator++()) and decrement operator creates
a litle problem: there are two version of each operator, as they may be used as postfix
qperator (&8.. *++) OF as prefix operator (e.g,, +43).
Used as postfix operator, the value's object is returned as rvalue, which is an expression
having @ fixed value: the post-incremented variable itself disappears from view. Used as
prefix operator, the variable is incremented, and its value is returned as /value, so it can
te altered immediately again. Whereas these characteristics are not required when the
operator is overloaded, it is strongly advised to implement thése characteristics in any
overloaded increment or decrement operator. :
* Overloaded inerement operators without parameters are prefix operators, and
should return references to the current object.
* Overloaded increment operators having an int parameter are posifix operators,
and should return the value the object has at the point the overloaded operator is
called as a constant value.
When the object has a more complex data organization using a copy constructor might be
preferred. For instance, assume we want to implement the postfix increment operator in
the class PersonData. Presumably, the PersonData class contains a complex inner data
organization. If the PersonData class would maintain a pointer Person*current to the
Person object that is currently selected, then the postfix increment operator for the class
PersonData could be implemented as-follows:
PersonData PersonData::operator++(int)
{
PersonData tmp(*this); g
incrementCurrent(); // increment ‘current’,
: //somehow.
return tmp; .
) "
‘A matter of concern here could be that this operation actually requires two calls to the
Copy constructor: first to keep the current state, then to copy the tmp object to the
@nonymous) return value. In some cases this double call of the copy constructor might
be avoidable, by defining a specialized constructor. E.g.
PersonData PersonData: :operator++t (int)
‘ return PersonData(*this, incrementCurrent ());
Here, ns current () is supposed to return the information which allows the
constructor th st its cureene data member to the pre-increment value, at the same time
bject.
Re i tual PersonData object ioe
ra ear a te call ff the increment operator using its overloaded function
inally it is noted that the call 0 in tie
Name might ire us to provide an (any) int argument to inform the compiler that we
requ
Want the postfix increment function: E.8
PersonData p; 7/ incrementing
P = other.operator+t (i
OOP-63POPULAR PUBLICATIONS
//other', ‘then assigning ‘p'
P = other.operator++(0); // assigning ‘p', then
//inerementing ‘other’
b) #include //declarations of malloc and free
include
#include
using namespace std;
class C {
public:
cO; a
void* operator new (size_t size); //implicitly declared as a
static member function
void operator delete (void *p); //implicitly declared as a
static member function
Vi
void* C::operator new (size_t size) throw (const char *) (
void * p = malloc(size);
if (p 0) throw “allocation failure"; //instead of
std: :bad_alloc
return p;
perator delete (void *p) {
C* pe = static_cast(p);
free(p);
}
int main() (
C *p = new c; // calls c
ew
delete p; // calls C::delete
}
2. a) Why is it necessary to overload an operator? [MODEL QUESTION]
Answer:
Operator overloading is one of the many exciting features of C++ language. It is an
important technique that has enhanced the power of extensibility of C++. One important
feature of C++ is that, it tries to make the user-defined data types behave in much the
same way as the built-in types. For instance, C++ permits us to add two variables of user-
defined types with the same syntax that is applied to the basic types. Thhis means that C++
has the ability to provide the operators with a special meaning for a data type. The
mechanism of giving such special meanings to an operator is known as operator
overloading,
b) Give an example of binary operator overloading,
Answer: :
Binary operator overloading example:
#include
[MODEL QUESTION]
_ OOP-64