object oriented progamming in c++ [oop in cpp q&a]
TRANSCRIPT
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
1/76
QUESTIONS AND ANSWERS
FOR
OBJECT ORIENTEDPROGRAMMING IN C++
G.Appasami, M.Sc., M.C.A., M.Phil., M.Tech.,
Assistant Professor
Department of Computer Science and Engineering
Dr. Pauls Engineering Collage
Pauls Nagar, Villupuram
Tamilnadu, India.
SARUMATHI PUBLICATIONS
No. 109, Pillayar Kovil Street, Periya Kalapet
Pondicherry 605014, India
Phone: 0413 2656368
Mobile: 9786554175, 8940872274
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
2/76
First Edition: July 2010
Second Edition: July 2011
Published BySARUMATHI PUBLICATIONS
All rights reserved. No part of this publication can be reproduced or stored in any
form or by means of photocopy, recording or otherwise without the prior written
permission of the author.
Price Rs. 60/-
Copies can be had from
SARUMATHI PUBLICATIONS
No. 109, Pillayar Kovil Street, Periya Kalapet
Pondicherry 605014, India
Phone: 0413 2656368
Mobile: 9786554175, 8940872274
Printed at
Meenam Offset
Pondicherry 605014, India
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
3/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 1
OBJECT ORIENTED
PROGRAMMING IN C++
QUESTIONS
WITH
SHORT ANSWERS
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
4/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 2
1. Who developed C++?
C++ was developed at AT & T Bell laboratories in the early 1980s
by Bjarne Stroustrup. The name C++ (pronounced as C plus plus) was
coined by Rick Mascitti where ++ is the C increment operator.
2. Explain Basic Concepts of OOP2. List out the Salient features of OOP
2. Write the characteristics of OOP
2. List out the elements of OOP
The basic concepts of OOP are Class, object, Data abstraction,
Encapsulation, Inheritance, Polymorphism, Dynamic binding and message
passing.
Concept MeaningClass Class is a user defined data type
Object Object is an run time entity of class
Abstraction The act of representing essential features without
including the background details
Encapsulation The wrapping up of the data and functions into a
single unit (called class) is known as
encapsulation
Inheritance The mechanism of deriving a new class fromexisting class is called inheritance
Polymorphism The ability to take more than one form. More
operations in same name. polymorphism means
one name multiple forms
Dynamic binding The addresses of the functions are determined at
run time rather than compile time (late binding).
Linking of a procedure to execution code.
Message
Communication
Objects interaction by sending messages to each
other
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
5/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 3
3. What are the Applications of OOP?
Real time systems Simulation and modeling Object Oriented Data bases Hypertext, hypermedia and expert text AI and Expert Systems Neural networks and expert systems Desition support and office automation systems CIM/CAD/CAM Systems
4. How does a C++ Class differ from a C++ structure?
Structure Class
Default access is public Default access is private
Data Data & functions
Default inheritance type is public Default is private inheritance
5. What is namespace?
Namespace is a collection of classes arranged in a hierarchical
order. If we include more header files, then there is a chance to have same
classes in different files. This is a problem for compiler to select a class
from which header file. This problem is solved by standard namespace.
Ex.: using namespace std;
6. Write a simple C++ program to print a string on a screen
#include
main()
{
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
6/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 4
void getdata(void); //Function declaration
void display(void);
};
void person : : getdata(void) //Function definition
{ cout>name;
cout>age;
}
void person : : display(void)
{ coutsum;
The operator
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
7/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 5
9. Write the structure of C++ program
A typical C++ program would contain four sections as shown in the
figure.
10. What stream class is required to create an output stream?
Ostream classes is required to create an output stream.
Note: istream class for input. Iostream for input & output
11. What are the uses of void?
To specify the return type of function when it is not returning anyvalue.
To indicate an empty argument list to a function.12. What are the difference between normal variable and reference
variable?
S normal variable reference variable
1 It holds data It holds address
2 It is not a poiner It is a pointer to another variable.
3 It is a variable tostore value in
memory
It is a variable to store address ofanother variable in memory
4 Ex.: int x; Ex.: int *ptr;
13. Write C++ character set
Like the C language, C++ also comprises a character set from which
the tokens (basic types of elements essential for programming coding) are
constructed. The character set comprises of A .. Z , a .. z, 0 .. 9, +,
-, /, *,\, (, ), [, ], {, }, =, !=, , . , ; : %, ! , &, ?, _, #, =, @, white
space, horizontal tab, carriage return and other characters.
Include filesClass declaration
Class function definitions
Main function program
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
8/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 6
14. What is a TOKEN?
A token is the smallest individual unit in a program. Tokens are
classified as shown in Figure.
15. List out few key words in C++.
16. Explain operator and operand.
Operator specifies an operation to be performed that yields a value.
An operand is an entity on which an operator acts.
For example: RESULT = NUM1 + NUM2
NUM1 and NUM2 are operands. + is the additional operator, that
performs the addition of the numbers. The result (value) generated is stored
in the variable RESULT by virtue of = (Assignment) operator. Table
shows the operators in C++.
17. List out the operators in C++
The following operators are specific to C++.
:: .* ->* ::* new delete endl setw
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
9/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 7
18. List out the Advantages of new operator
1. New operator automatically computes the size of the dataobject. We need not use the size of operator.
2. It automatically returns the correct pointer type. So that there isno need to use a type cast.
3. It is possible to initialize the object while creating the memoryspace.
4. Like other operator, new and delete can be overloaded.19. List out the Operators classification.
Operators are classified as Arithmetic, Assignment, Component
Selection, Shift, Conditional Logical, Manipulator, Member
dereferencing, Preprocessor, Relational, Scope Resolution, Type Cast
Memory Management. etc
Based on operand requirements, operators are also classified as
Unary operators require one operand:
&, !, *, ++, --, +, -, ~.
Binary operator requires two operands:
+, -, *, /,
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
10/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 8
22. Can the precedence order of an operator be altered?
Yes, the precedence order of an operator can be altered by using
parenthesis.
23. Give an example for type cast operation
int avg, sum, num;
avg = sum / float(num);
Now num integer variable is promoted to float
24. Explain Expression with an example.
An expression is a combination of operators, constants and
variables arranged as per the rule of the language. It may also include
function call with return call. An expression may consist of one or moreoperands and zero or more operators to produce value.
Ex. A=(B/2)+(C*10.5)
25. What is an expression?
An expression is a program construct or operation created by
combination of operators and operands.
Ex.: C = A+ B
26. Write the types of expressions
There are four types of expressions. They are:
Constant expressions consist of only constant values
Ex.: 15 25+10/2.0 M
Integral expressions are those which produce integer results
Ex.: m*n-5 m-x 5+int(2.7)
Where m and n are integer variables
Float expressions are those which produce floating-point results
Ex.: x+y x*y/10 5+float(10)
Where x and y are floating-point variables
Pointer expressionsproduce address variablesEx.: &m *ptr ptr+1
Where m is a variable and ptr is a pointer
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
11/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 9
27. Write branching and looping statements?
Branching (Selection )
if, if-else and switch
Looping
while, do-while and for
28. What is implicit conversion?
28. What is automatic conversion?
Whenever data types are mixed in an expression, C++ performs the
conversions automatically. This process is known as implicit or automatic
conversion.
Consider an expression with mixed data types like m=5+2.75 is a
valid statement.
29. List out some basic data types in C++
Name Description Size* Range*
char Character or small integer. 1bytesigned: -128 to 127
unsigned: 0 to 255
short int
(short)Short Integer. 2bytes
signed: -32768 to 32767
unsigned: 0 to 65535
int Integer. 4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to
4294967295
long int
(long)Long integer. 4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to
4294967295
bool
Boolean value. It can take
one of two values: true or
false.
1byte true or false
float Floating point number. 4bytes+/- 3.4e +/- 38 (~7
digits)
doubleDouble precision floating
point number.8bytes
+/- 1.7e +/- 308 (~15
digits)
long
double
Long double precision
floating point number.8bytes
+/- 1.7e +/- 308 (~15
digits)
wchar_t Wide character.2 or4
bytes1 wide character
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
12/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 10
30. Define widening conversion
Converting from smaller data type to wider data type is called
widening conversion.
Conversion of a char or short int to int is called integer widening
conversion.
31. Explain water fall model of type conversionConverting from smaller data type to wider data type is called
widening conversion. Widening conversion is also called as water fall
model of type conversion. The water fall model is shown in the below
figure.
33. Explain function prototyping
Function prototyping is a declaration statement in the calling
program. The general form is as follows:
Example 1: float volume(int x, float y, float z);
Example 1: float area(float, float );
Short char
int
unsigned int
long int
unsigned long int
float
double
long double
Return-type function-name (argument-list);
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
13/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 11
33. What is call byValue?
If a function called with actual value is called call by value.
Ex. int swap (int a, int b)
34. What is call by reference? If a function called with reference variables is called call by
reference.
void swap (int &a, int &b)
{ int t =a;
a=b;
b=t;
}
swap (&x, &y);
Because it works on original data. x and y value gets change permanently.
35. What is return by reference?
A function returns a reference is known as return by reference
int & max(int &a, int &b)
{ if (a>b)
return a;
else
return b;
}
int * ptr = max(&x, &y)
this function may return address of x or y to ptr.
36. What is function overloading?Family of functions with one function name but with different
argument lists. Depending on the arguments correct function will be
invoked. This process is known as function overloading. This is also known
as function polymorphism (compile time polymorphism).EX: //declarations
add(int, int) //prototype1
add(float,float) //prototype2
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
14/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 12
add(int, float) //prototype3
//function call
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
15/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 13
39. What is friend function?The non member function is defined elsewhere in the program like a
normal C++ function. The function definition doest use either the key word
friend or the scope operator ::. The functions that are declared with the
keyword friend are known as friend function.
Ex:
class A
{ Int a[20];
Public:
getdata();
{for (int i=0;i>a[i];}
showdata();
{for (int i=0;i
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
16/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 14
43. What is constant argument?
If function arguments are declared as const. they the arguments are
called comstant argument. The function arguments should not modified in
some cases like interest rate.
float intamout (float p, int t, const float r=0.15)
This is important only when we pass arguments by reference or
pointer.
44. State the properties of static function?
A member function that is declared static has the following
properties:
A static function can have access to only other static members(variables and functions) declared in the same class.
A static member function can be called using the class name(instead of its objects) as follows:
Calss_name :: function_name;
45. Explain array of objects.Set of objects of same class with the same name and stored in
continuous memory locations
Array of objects are collection of objects of same class that are
referred by a common name.
Ex; class stack
{ Int top, a[20];
Public:
Push();
Pop();
}
Main()
{ Stack s[5];
---
}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
17/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 15
46. State the properties of static member functions
Static member functions can also be defined in the private region of
a class.
Private Static member functions can access only Static data
member and can invoke Static member functions .
47. What is abstract data type?An abstraction that describes a set of objects in terms of an
encapsulated or hidden data and operations on that data is called abstract
data type.
48. What is abstract data type?
Abstract collection of data elements and their accessing functions.
Classes use the concept of abstraction and are defined as a list of attributes
and functions to operate on these attributes. They encapsulate all the
essential properties of the objects. Since the classes use the concept of data
abstraction, they are known as abstract data types.
Ex: class stack
{
Int top, a[20];
Public:
Push();
Pop();
}
49. What are the different types of access specifiers?Class members can have the following access specifiers
Private is the default access and private members are accessible only from
the member functions of the same class and/or from their friend class.
Protected members are accessible from member function of the same class
and/or friend classes, and also from members of their immediate derived
class
Public members are accessible from anywhere the class is visible.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
18/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 16
50. What is data abstraction?
Data abstraction refers to the act of representing essential features
without including the background details or explanations.
51. Explain encapsulation
The wrapping up of data and functions into a single unit (called
class) is known as encapsulation.
The mechanism by which the data and functions are bound together
with in an object definition is called encapsulation.
52. What is a class? A class is a user defined data type. It is a blue print, which defines
the variable and methods common to all objects of a certain kind.
53. What is a class?
A group of objects that share common properties and relationships
is called class. In C++, A class is a new data type that contains member
variables and member functions that operate on the variables. A class is
defined with a keyword class.
54. What is an abstract class?
A class that serves only as abase class from which classes are
derived is called abstract class. No objects are created for abstract class.
A class contains a pure virtual functions is an abstract class.
55. What is a container class?
A class that contains objects of other classes is called container
class
56. What is an object?A variable whose type is a class is called an object.
An instance of a class is known as an object.
objects are Run time entities in object oriented programming
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
19/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 17
57. What is an instance?
An instance is an object of a particular class. The term instance and
objects are interchangeable. An object has state, behavior and identity,
State defines the attribute (data member) of an object.
Behavior defines method or function used to modify the state of an
object.
Identity is name of an object.
58. What is Call by reference? A function call mechanism that passes arguments to a function by
passing the address of the arguments.
59. What is Call by value? A function call mechanism that passes arguments to a function by
passing a copy of the values of the arguments.
60. Explain constructor with exampleA constructor is a special function whose task is to initialize the
objects of its class. It is special because its name is the same as the class.
Class stack
{
int top;
Public:stack()
{top =0;}
- - -
}
61. Explain destructor with exampleDestructor is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose
name is same as the class name but it is preceded by tilde.
~stack(){}
62. What are the main function return types?
void and integer
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
20/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 18
63. How constructors differ from normal functions?
A constructor is a member function of a class that is used to create
objects or initialize objects of that class. It has the same name as the class
itself, has no return type and is invoked while creating the objects.
A method is an ordinary function of a class. it has its own name, a
return type and is invoked explicitly using the dot operator.
64. List out the properties of constructors
1. Constructors should be declared in public section.
2. They are invoked automatically when objects are created
3. They do not have return type.
4. They must use name of the class.
65. What are the difference between default and parameterized
constructors?
The constructors which does not take arguments explicitly is called
default constructor.
Constructors with arguments are called parameterized constructors.
66. What are all the operators that cannot be overloaded?Direct member access operator .
De-reference pointer to class member operator .*
Scope resolution operator ::
Conational operator ?:
Size of operator Sizeof
67. Explain type conversion
Converting data from one type to another type is called type
conversion. Three types of data type conversions are
A. Conversion from built-in type to class type.B. Conversion from class type to built-in type.
C. Conversion from one class type to another class type.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
21/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 19
68. What is the use of virtual base class?
The duplication of inherited members due to multi paths can be
avoided by making the common base class (ancestor class).
69. What is the use of public access mode?
Public accessible members can be accessed from outside the class.
70. What is the default access mode in a class?
Private is the default access mode in a class
71. What are the functions supported by file stream class for
performing I/O operations?
Put() get() open() close() read() write()
72. What are the file ptr functions available in C++
what are the functions for manipulation of file pointers?
seekg() -> indicates the file pointer position moved by
the get pointer
seekp() -> indicates the file pointer position moved by
the put pointer
tellg() -> tells the file position moved by get pointer
tellp() -> tells the file position moved by put pointer
73. What are the file stream classes available in C++?
fstream, ifstream, ofstream, fstreambase and filebuf
74. What is an I/O stream?
A stream is a sequence of bytes. The source stream that
supplies data to the program is called input stream and the destination
stream that receives data from the program is called output stream.
75. What is dynamic initialization?
C++ permits initialization of variables at run time. This is
referred as dynamic initialization.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
22/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 20
OBJECT ORIENTED
PROGRAMMING IN C++
QUESTIONS
WITH
DESCRIPTIVE ANSWERS
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
23/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 21
1. Explain the basic concepts of OOP
The basic concepts of OOP are Class, object, Data abstraction,
Encapsulation, Inheritance, Polymorphism, Dynamic binding and message
passing.
A. Class
A group of objects that share common properties and relationships
is called class. A class is a new data type that contains member variables
and member functions that operate on the variables. A class is defined with
a keyword class.
A class is a user defined data type. It is a blue print for objects,
which defines the variable and methods common to all objects of a certain
kind.
Example: person class:
class person //New data type class person
{
char name[30]; //Data member
int age; //Data member
public: //Public access
void getdata(void); //Function declaration
void display(void);
};
B. Objects
The class variables are known as objects. An instance of a class is
known as an object. Objects are Run time entities in object oriented
programming
Example: person object p:
main()
{
person p; //Person object
p.getdata();
p.display();}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
24/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 22
C. Data abstraction
The act of representing essential features without including the
background details or explanations is known as data abstraction. Class uses
the concept of abstraction. Since class uses the concept of data abstraction,
they are known as Abstract Data Types.
D. Encapsulation
The wrapping up of the 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 objects data and the program. This
insulation of the data from direct access by the program is called data
hiding.
E. Inheritance
The mechanism of deriving a new class from existing class is called
inheritance. There are different kinds of inheritance namely single,
multiple, multilevel inheritance, Hierarchical and Hybrid
Ex.: Single Inheritance
A derived class with only one base class is called Single Inheritance
Class Child : public Parent
F. Polymorphism
The ability to take more than one form is called polymorphism.
That is, more operations in same name. Polymorphism means one name
with multiple forms. Run time polymorphism and compile time
polymorphism are the two kinds of polymorphism.
Parent
Child
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
25/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 23
G. Dynamic binding
The addresses of the functions are determined at run time ratherthan compile time (late binding). Linking of a procedure to execution code
is done at run time is called dynamic binding.
H. Message Communication
Objects communicate with one another by sending and receiving
information. A message for an object is a request for execution of
procedure. Message passing involves specifying the name of the object, the
name of the function (message) and information to be sent. Example is
given below :
Polymorphism
Compile timePolymorphism
Run timePolymorphism
Function
overloading
Operator
overloading
Virtual
functions
employee . salary (name);
object message Information
ob ect
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
26/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 24
2. What are the Principal Advantages of OOP?2. What are the merits of OOP Methodology?
2. What are the Benefits of OOP/OOM?
OOP offers several befits to both the program designer and the user.The principal advantages are:
Through inheritance, we can eliminate redundant codeand extend the use of existing classes
We can build programs from the standard working modules(Reusability of code by Inheritance).
The principle of Data hiding (encapsulation) helps programmerto build secure program.
Program developed by modules through classesIt is possible to have multiple instances of class objects to co-
exist without any interface.
It is possible to map objects in the problem domain to thoseobjects in the program.
It is easy to Portion the work based on objectsData centered and Bottom-Up design approach.Object oriented systems can be easily upgraded from small to
large systems.
Message passing technique for communication between objects.Software complexity can be easily managed.
3. Explain object oriented programming paradigm
3. Explain object oriented programming approach
3. Explain object oriented programming Methodology
Object oriented programming approach provides solution to some
of flaws encountered in procedural approach. OOP treats data as a critical
element in the program development and does not allow it to flow freely
around the system. It ties data more closely to the functions that operates on
it and protects it from accidental modification from outside functions.
OOP allows decomposition of a problem into a number of entities
called objects and then builds data and functions around these entities. The
organization of data and functions in OOP is shown in the figure given
below:
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
27/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 25
The data of an object can be accessed only by the functions
associated with that object. However, functions of one object can access thefunction of other objects.
Some of the striking features of OOP are:
Emphasis is on data rather than procedure. Programs are divided into elements called objects. Data structures are designed such that they characterize the
objects (Abstraction).
Functions and data tied together into a single unit calledencapsulation.
Data is hidden (private data) and cannot be accessed byexternal functions.
Objects may communicate with each other through functions. New data and functions can be easily added whenever
necessary (inheritance).
Bottom-up approach in program design.OOP is the most recent concept among programming paradigms.
Class and objects are the building blocks in OOP. An object is considered
to be a partitioned area of computer memory that stores data and set of
operations that can access that data.
Data
Functions
Object A
Data
Functions
Object B
Data
Functions
Object C
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
28/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 26
4. Write the difference between C & C++.
C:
C is a Procedural Programming. It was developed at AT & T Bell
laboratories in 1972 by Dennies Ritchie From the language B.
C++:
C++ is an Object Oriented Programming. It was developed at AT
& T Bell laboratories in the early 1980s by Bjarne Stroustrup.from the
languages C and Simula67.
C C++
C is a subset of C++ C++ is super set
Procedure Oriented
Programming (POP)
Object Oriented Programming (OOP)
Top down approach Bottom up approach
Structured Programming Modular Programming
Importance in given for program Importance is given for data
Does not support objects Supports objects
C provides
Action/Structure/function
oriented programming
C++ provides Object Oriented
Programming with features like
Abstraction, Encapsulation,
Inheritance and polymorphism
C is not a strong type checkinglanguage
C++ is a strong type checkinglanguage
C does not supports error
handling
C++ supports sophisticated error
handling using the Exception Handling
Function overloading and
function overriding are not
availed in C
Function overloading and function
overriding can be done in C++
C does not supports Templates C++ supports Templates
Scanf & printf functions for
getting and showing values
Cin and cout stream operators for
getting and showing values
Input and out put format like
%d, %f, %c are required in
I/O process
No format is required in c++ in I/O
process
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
29/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 27
5. Explain Data Types in C++Data Types are the kind of data that variables hold in a
programming language. The ability to divide data into different types in
C++ enables one to work easily with complex objects.
C++ Basic Data Types and their size in bytes
Type Bytes
char, unsigned char and signed char 1int, unsigned int, signed int and short int 2
long int, unsigned long int and signed long int 4
float 4
double 8
long double 10
char and signed char value varies from -128 to 127
unsigned char value varies from 0 to 255
int and signed int value varies from -32768 to 32767
unsigned int value varies from 0 to 65535
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
30/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 28
6. Explain Storage Class / Storage Specifiers
Storage Class is another qualifier (like long or unsigned) that can be
added to a variable declaration. The four storage specifiers are auto, static,
extern and register. static and register variables are automatically
initialized to zero when they are declared. Auto variables are not initialized
with appropriate values based on their data type. These variables get
undefined values known as garbage.
Storage Meaning Example
auto Defines local variable known to
the block in which they are
defined. By default the local
variables are auto hence rarely
used.
void main()
{ autofloat ratio;
int kount;
}
static Global scope but one time
initialization
void fun()
{
static int x;
x++;
}
extern Global variable known to all
functions in the current program. These variables are
defined in another program.
extern int filemode;
extern void factorial();
register The modifier register instructs
the compiler to store the
variable in the CPU register to
optimize access.
void fun()
{register int I;}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
31/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 29
7. What are the difference between break and continue?
Break statement tells to compiler that to exit from a loop or switch
case. If loops are nested, the break would only exit from the loop
containing it. That is, break will exit only a single loop. Break statement at
the end of the switch case causes an exit from the switch statement.
The continue statement tells to compiler that to skip the remaining
statements and continue with next iteration.
Break Continue
Break will exit only from a single
loop
Continue will skip remaining lines
for one iteration.
Used in loop and branch control Used only in loop control
Loop is terminated Loop is continued
while(test-con)
{---------
if(cond)
break;--------
}
while(test-con)
{---------
if(cond)
continue;
--------
}
for(ini;test;inc){
---------
if(cond)continue;
--------
}
switch(expresion)
{case 1:
block1
break;case 2:
}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
32/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 30
8. Explain Control Structures in C++
Statements in a program need not necessarily be executed in a
sequential order. Some segments in a program are executed based on a
condition. In such situations the flow of control jumps from one part of the
program to another. Program statements that cause such jumps are called as
control statements or control structures.
Control structures
Sequence Selection (Decision making & Branching)
Control structure
SequenceSelection Loop structure
if ,if else switch do-while while, for
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
33/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 31
Loop
IF (Branch)
if (expression is true){
action 1;
}
action 2;
action 3;
If(age>60){
Int_rate=Int_rate+0.5;
}
Interest=P*y*Int_rate;
Cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
34/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 32
SWITCH (Multiple branches)
switch (expression )
{
case 1:
{
action 1;
}
case 2:
{
action 2;
}
case 3:
{action 3;
}
default:
{
action 4;
}
}
action 5;
Switch(option)
{
case 1:
{
Push();
}
case 2:
{
Pop();
}
case 3:
{Display();
}
default:
{
Cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
35/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 33
The do-while is an exit-controlled loop. Based on the true condition, the
control is transferred to back to loop.
WHILE (entry controlled loop)
while(condition is
true)
{
action 1;
}
action 2;
Int n=100,sum=0, i=0;
while(i
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
36/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 34
9. Explain Classes and objects with example
Class
The most important feature of C++ is the Class. Its significance is
highlighted by the fact that Bjarne Stroustrup initially gave the name Cwith Classes . A class is a new way of creating and implementing a user
defined data type.
A group of objects that share common properties and relationships
is called class. In C++, A class is a new data type that contains member
variables and member functions that operate on the variables. A class is
defined with a keyword class.
A class is a user defined data type. It is a blue print for objects,
which defines the variable and methods common to all objects of a certain
kind.
Characteristics of a class:
The keyword class specifies user defined data type class name The body of a class is enclosed within braces and is
terminated by a semicolon
The class body contains the declaration of variables andfunctions
The class body has three access specifiers ( visibility labels)viz., private , public and protected
Specifying private visibility label is optional. By default themembers will be treated as private if a visibility label is not
mentioned
The members that have been declared as private, can beaccessed only from within the class
The members that have been declared as protected can beaccessed from within the class, and the members of the
inherited classes.
The members that have been declared as public can beaccessed from outside the class also
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
37/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 35
Structure of a class
Class Name
Data Declaration
Function
Declaration
Function
Definition
#include
class item //class declaration
{
int number; //private data member
float cost; //private data member
public:
void getdata (void);//prototype declaration
void putdata(void); //function defined here
};
void item :: getdata (void) //function definition
{
coutnumber;
coutcost;
}
void item :: putdata (void) //function definition{
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
38/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 36
main()
{
item x; //create object
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
39/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 37
Array of objects
item x[100];
The above line will create 100 arrays of objects of type item.
The below lines will collects data for 100 objects.
for(int i=0;i
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
40/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 38
10. Explain constructor and destructor with suitable example Constructor
A constructor is a special function whose task is to initialize the
objects of its class. It is special because its name is the same as the class.
Class stack
Class stack
{ Int top;
Public:
stack(); //constructor
~ stack(); //destructor
push();
pop();
disp();
- - - -
};
Example: Constructor
stack ::stack()
{
top=0;
}
Special characteristics of constructors:
They should be declared in public section. They are invoked automatically when the objects are created. They do not have return types. So they cannot return values. They cannot be inherited. Like other C++ functions, they can have default arguments. Constructors cannot be virtual. We cannot refer to their addresses.
Types of Constructors
1. Parameterized constructors
The constructors that can take arguments are called parameterized
constructors.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
41/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 39
class integer
{ int m,n;
public:
integer(int x, int y) //parameterized constructor
..}
2. Default constructors
A constructor that accepts no parameter is called default
constructor. the default constructor for a class A is:
A::A().
3. Multiple constructors
More than one constructor with different arguments is called
multiple constructors.
class integer
{ int m,n;
public:
integer() {m=0; n=0;} // constructor1
integer(int x, int y) // constructor2
{m=a;n=b;}
integer(integer &i) // constructor3
{m=i.m;n=i.n;}
..
}
4. Default arguments constructors
A constructor with default argument is called default argument
constructor.
class complex
{ float real, imag;
public:
complex(float real, float imag=0);
.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
42/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 40
}
complex c(5.0)
real variable gets 5.0 and imag variable get 0 (by default)
5. Dynamic initialization of objects
the class objects can be initialized dynamically too. that is, the
initial value of an object may be provided during run time.
stack ::stack()
{
top=0;
}
6. Copy constructor
A constructor can accept a reference to its own class as a parameter.
that is,
Class A
{
.
public:
A(A &);
}
A copy constructor is used to declare and initialize an object from another
object.
7. Dynamic constructors
Allocation of memory to objects at the time of their construction is
known as dynamic construction for objects. The memory is allocated with
the help of the new operator.
Destructor
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
43/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 41
A Destructor is used to destroy the objects that have been created
by a constructor. Like a constructor, the destructor is a member function
whose name is same as the class name but it is preceded by tilde.
Example: Destructor
~stack()
{
delete st;
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
44/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 42
11. Compare and contrast between constructor and destructor?
Constructor and destructor
Constructor Destructor
SimilaritiesConstructors does not have a return
type
Destructor also does not have a
return type
Constructor is a member function to
a class
Destructor is also a member
function to a class
Constructor uses class name as their
names
Destructor also uses class name as
their with ~ .
Differences
Provided to a class to initialize an
object
Cleans up or de-initializes each
object before object is destroyed
It has same name as its class It has same name as its class with
prefixed ~ (tilde)
Constructors can have arguments Destructor has no arguments
Multiple constructors can exists Multiple destructors can not exists
Constructors can be overloaded Destructors can not be overloaded
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
45/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 43
12. What is function overloading?Many functions with same name created to perform different tasks.
Family of functions with one function name but with different
argument lists. Depending on the arguments correct function will be
invoked. This process is known as function overloading. This is also known
as function polymorphism (compile time polymorphism).
#include
class sample
{
public:
int add(int, int); //prototype1
float add(float,float); //prototype2
add(int, float); //prototype3
};
int sample :: add (int x, int y)
{ return (x+y);}
float sample :: add (float x, float y)
{ return (x+y);}
float sample :: add (int x, float y)
{ return (x+y);}
main(){ sample s;
//function call
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
46/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 44
13. Explain Operator overloading with an exampleC++ permits us to add two variables of user-defined types with the
same syntax that is applied to the basic types. this means that C++ has the
ability to provide the operators with a special meaning for a data type. The
mechanism of giving such a special meanings to an operator is known as
operator overloading.
Operator overloading can be done with the help of a special
function is called operator function. The general form of operator function
is given below:
Where returntype is the type of value retuned by the specified operation
and op is the operator being overloaded. the op is proceeded by he keywordoperator.
Operatorop is the function name.
Operator function must be either member functions (non static) or
friend function.
List of operators that cannot be overloaded are:
Direct member access operator .
De-reference pointer to class member operator .*
Scope resolution operator ::
Conational operator ?:Size of operator Sizeof
List of friend function cannot be used are:
Assignment operator =
Function call operator ()
Subscripting operator []
Class member access operator ->
.
Operator functions are declared as follows:
vector operator + (vector); // vector addition
vector operator - (); // unary minus
friend vector operator + (vector, vector); // vector addition
friend vector operator - (vector); // unary minus
returntype classname :: operator op (arg-list){
Function body //task defined
}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
47/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 45
int operator == (vector) //comparison
friend int operator == (vector, vector) //comparison
Rules for overloading operators:
Although it looks simple to redefine the operators, there are somerestrictions and limitations in operator overloading. Some of them are listed
below:
1. Only existing operators can be overloaded. New operators cannot becreated.
2. The overloaded operator must have at least one operand that is ofuser defined type.
3. We cannot change the basic meaning of the operator.4. Overloaded operators must follow the rules of the original
operators.
5. There are some operators that cannot be overloaded.6. We cannot use friend functions to overload certain operators.7. Unary operators are overloaded by means of a member function
with out argument.
8. Binary operators are overloaded through a member function withone argument and a fiend function with two arguments.
9. The left-hand operand must be an object for binary operatoroverloading.
10.Binary arithmetic operators such as + - * and / must return a value.Example1: Program for unary operator overloading
The unary operator is overloaded with single operand. The unary
operator is used to change the negative value of the operand.
Overloading unary operators
#include
class point
{
int x;
int y;
public:
void getdata(int a , int b);
void display(void);
void operator - (); //// unary minus
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
48/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 46
};
void point :: getdata(int a, int b)
{
x=a; y=b;
}void point :: display(void)
{
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
49/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 47
public:
complex(){ } //constructor1
complex(float real, float imag) //constructor2
{
x=real;y=imag;
}
complex operator+(complex);
complex operator*(complex);
void display(void);
};
complex complex :: operator+(complex c)
{
complex temp; //temprary
temp.x=x+c.x; //real part addition
temp.y=y+c.y; //imaginary part addition
return temp;
}
complex complex :: operator*(complex c)
{
complex temp; //temprary
temp.x=(x*c.x)-(y*c.y); //real part multiplication
temp.y=(x*c.y)+(y*c.x); //imaginary part multiplication
return temp;
}
void complex :: display(void)
{
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
50/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 48
c4=c1*c2; //invoke operator*()
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
51/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 49
14. Explain type conversion with example
Converting data from one type to another type is called type
conversion. Three types of data type conversions are
A. Conversion from built-in type to class type.
B. Conversion from class type to built-in type.
C. Conversion from one class type to another class type.
Conversion takes place inConversion
required Source class Destination
class
Basic ->
Class
Not
applicable
Constructor
Class ->Basic
Castingoperator
Notapplicable
Class ->
Class
Casting
operator
Constructor
A. Basic to Class Type
The conversion from basic type to class type is easy to accomplish.
We can use constructor to build a string type object from a char* type
variable. This is an example fordefacto type conversion.
Class String constructor:
The string constructor builds a string type object from char* type
variable a. The variables length and p are data members of the class string.
This constructor is used for conversation from basic data type char * to
string type.
string :: string(char *a)
{ length = strlen(a);
P = new char[length + 1];
strcpy(P,a);
}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
52/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 50
Example:
The last statements are used to converts data from char * type to string
type.
B. Class to Basic Type
C++ allows us to define a overload a casting operator that could be
used to convert a class type to a basic type. The general form of an
overloaded casting operator function, usually referred to as a conversionfunction, is:
Example: Converstion from class type string to basic type char * as
follows:
string s3=Dr Pauls Engineering College
char * name3=char* (s3); or
char * name3=s3;
C. One Class to Another Class
We have seen data conversion technique from a basic to class type
and a class to basic type. But there are situations where we would like toconvert one class type data to another class type.
Example:
operator typename()
{
(Function staetments )
}
objX = objY; //ob ects of different t es
string s1,s2;
char * name1 = Dr Pauls;
char * name2 = Engineering College;
s1=string(name1); //calls constructors2=name2; //implicitly calls constructor
string : : operator char*()
{return(p);
}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
53/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 51
Where objX is an object of class X and objY is an object of class Y. The
class Y type data is converted to the class X type data and the converted
value is assigned to the objX. Since the conversion takes place from class
Y to class X, Class Y is Known as source Class and Class X is known as
the destination Class.Such conversions between objects of different classes can be carried
out by either a constructor or a conversion function.
//polar to cartesian.cpp
#include
#include
#include
class polar
{ public:
float r;
float a;
polar(float i=0, float j=0) //constructor
{ r=i;
a=j;
}
};
class cartesian
{
public:
float x;
float y;
cartesian(float m=0, float n=0) //constructor
{ x=m;
y=n;
}
cartesian(polar p) //type conversion
{ x=p.r*cos(p.a);
y=p.r*sin(p.a);
}
void show()
{
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
54/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 52
void main()
{
polar ppoint(4.25,0.785); //angle PI/4=0.785
cartesian cpoint;
cpoint=ppoint; //Polar object is assignedcpoint.show();
getch();
}
Output
( 3.0005, 3.0004 )
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
55/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 53
15. Explain inheritance / Extending Classes
The mechanism of deriving a new class from existing class is called
inheritance. The existing class is known as base class, super class or parent
class; the new class is known as sub class, derived class or child class.
Defining derived classes
A derived class is defined by specifying its relationship with the base class
in addition to its own details. The general form of defining a derived class
is:
class derived_clas_name : visibility_mode base_class_name
{
//members of derived classes
}
Types of Inheritance
There are different kinds of inheritance namely single, multiple, multilevel
inheritance, Hierarchical and Hybrid
Single Inheritance means a class derived from only one of existing class.
(A derived class with only one base class is called Single Inheritance)
Class Child : public Parent
{ . . .};
Multilevel Inheritance means a class derived from only one of existing
class.
Parent
Derived1
Derived2
Parent
Child
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
56/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 54
Class Derived1 : public Parent
{ . . .};
Class Derived2 : public Derived1
{ . . .};
Multiplelevel Inheritance means a class derived from more than one ofexisting classes.
Class Derived1 : public Parent1, public Parent2
{ . . .};
Hierarchical Inheritance means a class my be inherited by more than one
classes.
Class Derived1 : public Parent1
{ . . .};
Class Derived2 : public Parent1
{ . . .};
Class Derived3 : public Parent1
{ . . .};
Hybrid Inheritance means combinations of the above inheritance.
Class Parent1 : public GrandParent1
{ . . .};
Class Parent2 : public GrandParent1
Parent1
GrandParent1
Derived3
Parent2
Derived1
Parent1
Derived2 Derived3
Parent1 Parent2
Derived1
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
57/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 55
{ . . .};
Class Derived3 : public Parent1, public Parent12
{ . . .};
Multi path inheritance / Virtual base classes
The child has two direct base classes parent1 and parent2 which
themselves have a common base class Grandparent. The child inherits
the traits ofGrandparent via two separate paths. It can also inherit directly
as shown by a broken line. The Grandparent is sometimes referred to as
indirect base class.
Inheritance by the child as shown in the above figure might pose
some problems. All the public and protected members of Grandparent are
inherited into child twice, first via parent1 and again via parent2. This
means child would have duplicate sets of the members inherited from
grandparent. This introduces ambiguity and should be avoided.
The duplication of inherited members due to this multiple paths
can be avoided by making the common base class (ancestor class ) as
virtual base class while declaring the direct or intermediate base classes as
shown below:
Class A // Grandparent
{};
Class B1: virtual public A //parent1
{};
Class B2: public virtual A //parent2
{};
Class C: public B1, public B2 //child{
//only one copy of a will be inherited
};
Derived1
Grand Parent
Child
Derived2
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
58/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 56
Access mode in inheritance
With in
class
With
derived
class
Main /
other class
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes
Private and public inheritance
Data public
derived
class
protected
derived
class
Private
derived
class
Private not
accessible
not
accessible
not
accessible
Protected protected protected Private
Public public protected Private
Sample program for hybrid inheritance
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
59/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 57
16. Explain pointers in C++
Pointers
Pointers data type is one of the strengths of the C++ language. A
pointer is a variable which holds the memory address of another variable.
The advantages of pointers
Pointer allows passing variables, arrays, functions, strings and structuresas function arguments.
Pointer facilitates functions to modify calling argumentsPointer supports dynamic allocation and de allocation of memory
segments.
It allows to establish links between data elements such as linked lists,stacks, queues, trees and graphs.
Initialization and declaration of pointers
int *ip; //integer pointer declaration
ip = & x; //address of x assigned to ip
*ip =50 //50 assigned to x through indirection
Constant pointer
char * const ptr1 = GOOD; // constant pointer
we cannot modify the address of ptr1
Pointer to a constant
int const * ptr =&m; // Pointer to a constant
ptr2 can point to any variable, but the contents of what it points to cannot
be changed.
Pointers to objects
#include
Class Base
{ public:void display() { cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
60/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 58
main()
{
Base B; Base *ptr; //declarations
coutdisplay() //calls Base version
ptr->show() //calls Base version
}
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
61/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 59
17. Explain virtual function
Same function name in both the base and derived classes,
the function in the base class is declared as virtual, C++ determines which
function to use at run time based on the type of object pointed to by the
base pointer, rather then the type of the pointer. Thus by making the base
pointer to point to different objects, we can execute different versions of
virtual function
It is used for late binding. That is, for run time polymorphism.
Example
#include
Class Base
{ public:
void display() { cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
62/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 60
Output
Ptr points to base
display base
show base
Ptr points to deriveddisplay base
show derived
Ptr is always point to base object. but run time polymorphism is achieved
by adding a key word virtual to show() function in base class.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
63/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 61
18. Explain virtual functions with a program (16)
Run time polymorphism is achieved by the concept of
virtual functions. Run time polymorphism refers to the property by which
Objects belonging to different classes are able to respond to the same
function in different forms. An essential requirement of polymorphism is
the ability to refer to objects without any regard to their class. This
necessitates the use of a single pointer variable to refer to the objects of
different classes.
Here we use the pointer to base class to refer to all the derived
objects. But we just discovered that a base pointer, even when it is made to
contain the address of a derived class, always executes the function in the
base class. The compiler simply ignores the contents of the pointer and
chooses the member function that matches the type of the pointer. How do
we then achieve polymorphism? It is achieved using what is known as
virtual function.
Same function name in both the base and derived classes, the
function in the base class is declared as virtual, C++ determines which
function to use at run time based on the type of object pointed to by the
base pointer, rather then the type of the pointer. Thus by making the base
pointer to point to different objects, we can execute different versions of
virtual function
It is used for late binding. That is, for run time polymorphism. run
time polymorphism is achieved only when a virtual function is accessed
through a pointer to the base class.
Example:
Consider a book shop which sells both books and video-tapes. We can
create a class known as media that stores the title and price of a publication.
We can then create two derived classes, one for storing the number of
pages in a book and another for storing the playing time of a tape. The
following figure shows class hierarchy for the book shop
mediavirtual void display()
book tape
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
64/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 62
//run time polymorphism-virtual functions
#include
#include
class media
{ protected:char title[50];
float price;
public:
media(char *s, float a)
{ strcpy(title,s);
price=a;
}
virtual void display() { } //empty virtual function
};
class book : public media
{ int pages;
public:
book (char * s, float a, int p) :media(s,a)
{ pages = p;
}
void display()
{ cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
65/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 63
main()
{ char *title;
float price, time;
int pages;
cout title;
cout > pages ;
cout > price;
book b1(title, price,pages);
cout title;
cout > time ;
cout > price;
tape t1(title, price,time);
media* m1;
media *m2;
m1=&b1;
m2=&t1;
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
66/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 64
19. Explain polymorphism
The ability to take more than one form is called polymorphism.
That is, more operations in same name. Polymorphism means one name
with multiple forms. The concept of polymorphism is implemented using
the overloaded functions and operators. Polymorphism can be divided into
Run time polymorphism and compile time polymorphism.
Compile time polymorphism
The overloaded member functions are selected for invoking by
matching arguments by number of arguments and its type. This information
is known to the compiler at the compile time and, therefore, compiler is
able to select the appropriate function for a particular call at the compile
time itself. This is called early binding orstatic binding orstatic linking.
Also known as compile time polymorphism. Early binding simply means
that an object is bound to its function at compile time.
Run time polymorphism
Consider the base and derived class with same function name and
prototype in both classes.
class A
{ int x;
public:
void show() {} //show() in base class
};class B : public A
{ int y;
public:
Polymorphism
Function
overloading
Operator
overloading
Virtual
functions
Compile time
Polymorphism
Run time
Polymorphism
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
67/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 65
void show() {} //show() in derived class
};
Here the same show() function is available in both classes. That is,
function overloading is not possible. Therefore static binding fails. In fact,the compiler does not know which function to chose.
The process of selecting the appropriate member function at run
time is called run time poly morphism. It can be achieved using virtual
functions. It is also called as late binding ordynamic binding
Thus, Run time polymorphism refers to the property by which
Objects belonging to different classes are able to respond to the same
function in different forms. Dynamic binding is the one of the powerful
features of C++. This requires the use of pointers to objects.
NOTE: for 16 mark write function overloading, operator overloading and
virtual functions.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
68/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 66
write data
(to files)
get data
(from key
board)
cin>>
20. Explain file handling
Introduction
File input and output streams
The I/O system of C++ handles file operations which are
very much similar to the console input and out put operations. It uses file
stream (sequence of bits or bytes) as an interface between the programs and
the files. The stream that supplies data to the program is known as input
stream and the one that receives data from the program is known as output
stream.
Stream classes for file operations
put datato screen
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
69/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 67
Details of stream classes
Class Contents
filebuf Its purpose is to set the file buffers to
read and write.
fstreambase Provides operations common to the file
streams.
ifstream Provides input operations
ofstream Provides output operations
fstream Provides support for simultaneous input
and output operations
//writing and reading objects in a file
#include
#include
class inventory
{
char name[10];
int code;
float cost;public:
void readdata (void);
void writedata(void);
};
ios
streambuf ostreamistream
iostream
fstream ofstreamifstream
fstream base
filebuf
iostream.h
file
fstream.h
file
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
70/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 68
void inventory :: readdata (void)
{
coutname;
coutcode;
coutcost;}
void inventory :: writedata (void)
{
cout
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
71/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 69
File mode parameters
No. Mode:
parameters
Meanings
1 ios :: in Open file for reading only2 ios :: out Open file for writing only
3 ios :: app Append to end-of-file
4 ios :: ate Go to end-of-file on opening
5 ios :: binary Open as binary file
6 ios :: nocreate Open fails if the file does not
exists
7 ios :: noreplace Open fails if the file already
exists
8 ios :: trunc Delete the contents of the file
if it exists
ERROR HANDLING DURING FILE OPERATIONS
We may get Errors when one of the following occurs:
A file which we are attempting to open for reading does not exist.The file name used for a new file may already exist.We may attempt an invalid operation such as reading after end-of file.There may not be any space in the disk for storing more data.We may use an invalid file name.We may attempt to perform an operation when file is not opened for that
purpose.
ERROR HANDLING FUNCTIONS
Function Return value and meanings
eof() Returns true (non-zero value) if end-of file is
encountered while reading; otherwise returns false
(zero).
fail() Returns true when input or output failed.
bad() Returns true when invalid operation or
unrecoverable error has occurred. if it is false, then
it may be possible to recover from error
good() Returns true if no error has occurred
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
72/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 70
21. Explain class and function templates
Single function or class for which a family of similar functions or
class in a generic manner is called templates.
Class template
A single generic class for set of multi class with similar objective is called
class template
Example
Template
T sum (T *arr, int n)
{
T temp=0;
for( int i=0;i
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
73/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 71
6. Explain Exception handling.
Exceptions are run time anomalies or unusual events like divide by
zero, out of range, index overflowing, running out of memory or disk space
error etc.
C++ supports exception handling mechanism to detect and manage
runtime errors.
Exceptions are classified into two major types. They are:
1. Synchronous
Error such as out of range, index overflowing, running out of
memory or disk space are called as synchronous type of exceptions.
2. Asynchronous
Events that are passed beyond the control of program such as
keyboard interrupts are called as Asynchronous.
Note: C+ supports Synchronous exceptions only.
There are two basic blocks to handle exceptions. They are1. Try -> to throw the exception
2. Catch -> to catch exception
Exce tions
Synchronous
Exceptions
Asynchronous
Exceptions
Normal code
code that
cause exception
yes
noexception
handler
Normal code
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
74/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 72
Syntax for Try block
try
{
.
throw(exception)}
Syntax for catch block
catch(argument type)
{
.
}
Steps involved in handling exceptions are:
1. Fix the problem
2. Inform that Error is occurred3. Receive error information
4. Take corrective action
Purpose of exception handling is to detect and report exception
circumstances, so that appropriate action can be taken. The mechanism
used in C++ to handle exception is throwing and catching exceptions.
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
75/76
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 73
22. Explain String manipulation in detail
STRINGS: A string is a sequence of characters. C++ does not
support string data type. But C++ provides a library header file for string
manipulation is called string.h. Using string.h we can easily perform stringoperations like copy, finding string length, finding substring, etc.
The string class is a very large and includes many constructors,
member functions and operators. We may use these constructors, member
functions and operators to achive the following.
Creating String objects Reading String objects Displaying String objects to the screen Finding a sub-string from a String modifying String objects Comparing String objects Adding String objects Accessing character in a string Obtaining the size of the string
Constructors
String() //create empty string
String(const char *str) //creating a String objects from a null-
terminated string
String(const string &str) //creating a String objects from a null-terminated string
Functions
append() at() compare() begin() end()
erase() find() insert() length() substr()
Operators
+, =, +=, ==, 1=, =
Examples
String s1 (Dr Pauls);String s2;
s2=s1;
s2=s1+Engineering College
-
8/3/2019 Object Oriented Progamming in C++ [OOP in CPP Q&A]
76/76
Biography
Mr. G. Appasami was born in Pondicherry, India in 1980. He received his Master of
Science degree in Mathematics, Master of Computer Applications degree and Master
of Technology degree in Computer Science and Engineering from Pondicherry
University, Pondicherry, India. He received his Master of Philosophy in Computer
Science from Alagappa University, Karaikudi, India.
Currently he is faculty in Dr. Pauls Engineering College, Villupuram and affiliated to
Anna University Chennai, Tamil Nadu, India. He is a life member of Indian Societyfor Technical Education, Computer Society of India, International Association of
Computer Science and Information Technology (Singapore) and International
Association of Engineers.
He also qualified Gate Exam. His Area of interests includes Network Security, image
processing and web technology. He has published more papers in national &
international journals and conference proceedings.
Email: [email protected]
Website: www.appas.110mb.com