Professional Documents
Culture Documents
Object-Oriented Programming 3 0 0 3
Object-Oriented Programming 3 0 0 3
Object-Oriented Programming 3 0 0 3
OBJECT-ORIENTED PROGRAMMING 3 0 0 3
(Common to CSE & IT)
Aim: To understand the concepts of object-oriented programming and master OOP using C++.
UNIT I
9
Object oriented programming concepts objects classes methods and messages abstraction and
encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access
specifiers function and data members default arguments function overloading friend functions const
2
and volatile functions - static members Objects pointers and objects constant objects nested classes
local classes
UNIT II
9
Constructors default constructor Parameterized constructors Constructor with dynamic allocation copy
constructor destructors operator overloading overloading through friend functions overloading the
assignment operator type conversion explicit constructor
UNIT III 9
3
Function and class templates - Exception handling try-catch-throw paradigm exception specification
terminate and unexpected functions Uncaught exception.
UNIT IV 9
Inheritance public, private, and protected derivations multiple inheritance - virtual base class abstract
class composite objects Runtime polymorphism virtual functions pure virtual functions RTTI typeid
dynamic casting RTTI and templates cross casting down casting .
UNIT V 9
Streams and formatted I/O I/O manipulators - file handling random access object serialization
namespaces - std namespace ANSI String Objects standard template library.
4
Total: 45
TEXT BOOKS:
REFERENCES:
1. Ira Pohl, Object Oriented Programming using C++, Pearson Education, Second Edition Reprint
2004..
5
2. S. B. Lippman, Josee Lajoie, Barbara E. Moo, C++ Primer, Fourth Edition, Pearson Education,
2005.
3. B. Stroustrup, The C++ Programming language, Third edition, Pearson Education, 2004.
6
UNIT I
9
Object oriented programming concepts objects classes methods and messages abstraction and
encapsulation inheritance abstract classes polymorphism.
Introduction to C++ classes access specifiers function and data members default arguments function
overloading friend functions const and volatile functions - static members Objects pointers and objects
constant objects nested classes local classes
7
2 Marks
1) Give the evolution diagram of OOPS concept.
Machine language
Procedure language
Assembly language
OOPS
known as Procedure oriented language (POP). In POP number of functions are written to accomplish the tasks
such as reading, calculating and printing.
Polymorphism.
Dynamic binding.
Message passing.
7)What is a class?
The entire set of data and code of an object can be made a user-defined data type with the help of a class.
11
Once a class has been defined, we can create any number of objects belonging to the classes.
Classes are user-defined data types and behave like built-in types of the programming language.
8) what is encapsulation?
Wrapping up of data and function within the structure is called as encapsulation.
means that the code associated with a given procedure call is not known until the time of the call at the run-
time.
Object-oriented databases.
AI and expert systems.
: : * Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator
Eg:
#include<iostream. h>
int m=10; // global variable m
void main ( )
{
int m=20; // local variable m
cout<<m=<<m<<\n;
cout<<: : m=<<: : m<<\n;
}
output:
20
21
10 (: : m access global m)
Scope resolution operator is used to define the function outside the class.
Syntax:
Return type <class name> : : <function name>
Eg:
Void x : : getdata()
23) What are free store operators (or) Memory management operators?
New and Delete operators are called as free store operators since they allocate the memory dynamically.
New operator can be used to create objects of any data type.
22
int n =strlen(string);
..
float area=3.14*rad*rad;
Thus declaration and initialization is done simultaneously at the place where the variable is used for the first
time.
function declaration;
};
Feature:
It is initialized to zero when the first object 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
It is only visible within the class, but its life time is the entire class type and scope of each static member
variable must be defined outside the class
It is stored separately rather than objects
Eg: static int count//count is initialized to zero when an object is created.
int classname::count;//definition of static data member
A static function can have access to only other static member declared in the same class
A static member function can be called using the classname as follows
classname ::function_name;
41) How the objects are used as function argument?
This can be done in two ways
A copy of the entire object is passed to the argument
Only address of the objects is transferred to the f unction
int m;
public:
void show( );
};
pointer to member m is defined as
int A::*ip=&A::m;
A::*->pointer to member of A class
&A::m->address of the m member of A class
};
student s1(a);
}
.
}
class student
{
};
student s1(a);}
PART-B
UNIT II
9
Constructors default constructor Parameterized constructors Constructor with dynamic allocation copy
constructor destructors operator overloading overloading through friend functions overloading the
assignment operator type conversion explicit constructor
47
1) Define constructor
A constructor is a special member function whose task is to initialize the objects of its class. It is special
because its name is same as class name. The constructor is invoked whenever an object of its associated class
is created. It is called constructor because it constructs the values of data members of the class
Eg:
integer Class
{
public:
integer( );//constructo r
48
.
};
integer::integer( )//default constructor
{
m=0;n=0;
}
the statement
integer a;
invokes the default constructor
length=0;
name=new char[ length +1];
}
void main( )
{
string name1(Louis),name3(Lagrange);
}
9) Define destructor
It is used to destroy the objects that have been created by constructor. Destructor name is same as class name
preceded by tilde symbol(~)
Eg;
~integer()
{
}
A destructor never takes any arguments nor it does it return any value. The compiler upon exit from the
57
program will invoke it. new Whenever operator is used to allocate memory in the constructor, we should
use delete to free that memory.
public:
integer( ) //default constructor
{
m=0;n=0;
}
integer(int a,int b) //parameterized constructor
{
m=a; n=b;
}
integer(&i) //copy constructor
{
59
m=i. m;
n=i.n;
}
void main()
{
integer i1; //invokes default constructor
integer i2(45,67);//invokes parameterized constructor
integer i3(i2); //invokes copy constructor
}
int p,q;
cin>>p>>q;
integer a(p,q);
function body
}
Since the return type of max ( ) is int & the function returns reference to x or y (and not the values). Then a
function call such as max ( a , b) will yield a reference to either a or b depending on their values.
The statement
max ( a , b) = -1;
is legal and assigns 1 to a if it is larger, otherwise 1 to b.
17) What is the purpose of using operator function? Write its syntax.
To define an additional task to an operator, we must specify what it means in relation to the class to which the
operator is applied. This is done by Operator function , which describes the task. Operator functions are either
member functions or friend functions. The general form is
65
19) How will you overload Unary & Binary operator using member functions?
When unary operators are overloaded using member functions it takes no explicit arguments and return no
explicit values. When binary operators are overloaded using member functions, it takes one explicit argument.
Also the left hand side operand must be an object of the relevant class.
20) How will you overload Unary and Binary operator using Friend functions?
When unary operators are overloaded using friend function, it takes one reference argument (object of the
relevant class) When binary operators are overloaded using friend function, it takes two explicit
arguments.
67
23) List out the operators that cannot be overloaded using Friend function.
68
Assignment operator =
Function call operator ( )
Subscripting operator [ ]
Class member access operator
int hrs,mins;
public:
.
Time ( int t) //constructor
{
hours= t/60 ; //t in minutes
mins =t % 60;
}
};
Constructor will be called automatically while creating objects so that this conversion is done automatically.
70
objX is the object of class X and objY is an object of class Y. The class Y type data is converted into class X
type data and the converted value is assigned to the obj X. Here class Y is the source class and class X is the
destination class.
72
PART-B
UNIT III 9
Function and class templates - Exception handling try-catch-throw paradigm exception specification
terminate and unexpected functions Uncaught exception.
Exceptions which occur during the program execution, due to some fault in the input data
Try block
ThrowInvoke
block function having throw block
If(failure)
Throw object;
80
exception
exception
Catch block
Catches all exceptions thrown from
within try block or by function
invoked within a try block
81
Keyword
try
{
//code raising exception or referring to a function raising exception
}
catch(type_id1)
{
//actions for handling an exception
}
83
catch(type_idn)
{
//actions for handling an exception
}
handler will only evaluate an exception that matches,or can be covered to the type specified in its argument
list.
Catch(T)
{
// actions for handling an exception
}
85
throw T;
10) List out the tasks to be performed for error handling code
1)Detect the problem causing exception(Hit the exception)
2)Inform that an error has occurred(Throw the exception)
3)Receive the error information(Catch the exception)
4)Take corrective actions(Handle the exceptions)
11) Write the steps to be performed when an exception is raised
1)The program searches for a matching handler
2)If a handler is found, the stack is unwound to that point
3)Program control is transferred to the handler
87
4)If no handler is found, the program will invoke the terminate()function. If no exceptions are thrown,
the program executes in the normal fashion
{
//Function body raising exceptions if error occurs
}
Catch()
89
{
//actions for handling an exception
}
A function template specifies how an individual function can be constructed. The limitation of
such functions is that they operate only on a particular data type. It can be overcome by defining that function
as a function template or generic function.
template<class T,>
ReturnType FuncName(arguments)
{
..//body of the function template
..
93
T1 data1;
.
//functions of template arguments T1,T2,.
void func1(T1 a,T2 &b);
PART-B
95
1) Discuss the need for exception with try, catch and throw keywords
2) What is Function Template? Write the syntax for function template. Write an example program for function
template.
3) What is class template? Write the syntax for class template. Write an example program for class template.
4) What are Exceptions? What are the two types of exceptions? Draw the Exception handling model?
5) What are uncaught exceptions? Write the functions to handle uncaught exceptions with a suitable example
6) What are Exceptions? What are the two types of exceptions? Write the syntax of try construct. Write the
syntax of catch construct. Write the syntax of throw construct with an example
96
UNIT IV 9
Inheritance public, private, and protected derivations multiple inheritance - virtual base class abstract
class composite objects Runtime polymorphism virtual functions pure virtual functions RTTI typeid
dynamic casting RTTI and templates cross casting down casting .
97
4)The base class public and protected member functions are considered as private member function in
derived class,when those class is privately inherited from base class
The class members are visible to the base class,derived classes and outside the class through the
objects
Eg:
Base class
Derived class
Here class A is the base class from which the class D is derived. Class D is the public
derivation of class B hence it inherits all the public members of B. But D cannot access
private members of B.
Derived class
Here class C is derived from two base classes A & B.
A
C
B
number from class student. Class test is derived from class Student. Class result is
derived from class Test and sports. As a virtual base class
Prototypes of base class version of a virtual function and all the derived class versions must be identical.
If a virtual function is defined in the base class, it need not be redefined in the derived class.
Polymorphism is the ability to take more than one form. An operation may exhibit different behaviors in
different. The behavior depends upon the type of data used.
Major Types
a.Run-time polymorphism
b.Compile time polymorphism
108
c.ad-hoc polymorphism
d.Parametric polymorphism
e.Virtual functions
f.Function name overloading
g.Operator overloading
b)Compound Type
c)Container Type
3)Property iterators
27)Define Downcasting
112
Downcasting is used to cast a pointer or reference to a base class to a derived class.Downcasting is the
opposite of the basic object-oriented rule,which states objects of a derived class,can always be assigned to
variables of a base class.Since base class variables can only sometimes be assigned to variables of a derived
class downcasting doesnt always work
28)Define Upcasting
Upcasting means classes can easily converge to a general class
PART-B
113
but not for both. Read(Input) the code for round (0 for morning and 1 for evening) and the number of total
paper rounds in one week done by a boy and compute his earning and display it.
6) What are the different kinds of inheritance? Explain them with suitable examples
7) Briefly explain RTTI
8) Describe virtual function with suitable example
9) Define pure virtual function
115
116
UNIT V 9
Streams and formatted I/O I/O manipulators - file handling random access object serialization
namespaces - std namespace ANSI String Objects standard template library.
ios Streambuf
*bp=&strstreambase::
bug
istream streambuf
ostream
iostream
b)hex
c)oct
d)es
e)endl
f)ends
g)flush
c)setfill(int fchar)
d)setbase(int base)
e)setiosflags(long flags)
f)resetioflags(long flags)
ios
iostream filebuf
13) What are the flags that do not have bit fields?
a)ios::showbase-Use base indicator on output
b)ios::showpos-Print + before positive integers
c)ios::showpoint-Show trailing decimal point and zeros
d)ios::uppercase-Use uppercase letters for hex output
e)ios::unitbuf-Flush all streams after insertion
g)ios::stdio-Flush stdout and stderr after insertion
14)What are the functions that the file stream class provides?
a)seekg()-Moves get pointer to a specified location
126
2)ios::out
3)ios::ate
4)ios::app
5)ios::trunk
6)ios::nocreate
7)ios::noreplace
8)ios::binary
ANSI C++ Standard has added a new keyword namespace to define a scope that could hold global
identifiers.The best example of namespace scope is the C++ Standard Library.All classes,functions and
templates are declared within the namespace named std.
Using namespace std;
The using namespace statement specifies that the members defined in std namespace will be used frequently
throughout the program
namespace namespace_name
129
{
//Declaration of
//variables,functions,classes,etc.
}
A container is an object that actually stores data.It is a way data is organized in memory. The STL
containers are implemented by template classes and therefore can be easily customized to hold different types
of data
An iterator is an object that points to an element in a container. We can use iterators to move through
the contents of containers.Iterators are handled just like pointers
Sequence containers store elements in a linear sequence, like a line. Each element is related to other
elements by its position along the line. They all expand themselves to allow insertion of elements and all of
them support a number of operations on them
3)deque
A map is a sequence of pairs where a single value is associated with each unique key. Retrieval of
values is based on the key and is very fast. We should specify the key to obtain the associated value.
Key1
Value1
Key2
138
Value2
. .
. .
. .
. .
. .
.
Key N . ValueN
139
8) size()
9) swap()
PART-B
1) Write a program to write and read data in a file using object I/O functions write( ) and read( ).
Declare class with data members name [2], m int bill no, int _amount debited and int received _
amount and in balance. Add 10 records and display the list of persons with balances. The user should
have a facility to modify the existing records Describe the various file modes and its syntax
141