Post on 22-Mar-2018
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 1
LABORATORY MANUAL
OBJECT ORIENTED AND MULTICORE
PROGRAMMING LABORATORY
SE-COMP
SEMESTER-II
TEACHING SCHEME EXAMINATION
SCHEME
Lectures: 3 Hrs/Week Theory: 50 Marks
Practical: 2 Hrs/Week On-Line: 50 Marks
Practical: 50 Marks
Term Work: 25 Marks
DEPARTMENT OF COMPUTER ENGINEERING
DNYANGANGA COLLEGE OF ENGINEERING AND
RESEARCH, PUNE
2014-2015
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 2
LIST OF ASSIGNMENTS
Subject: Object Oriented and Multicore Programming Subject Code: 210247
Group A
1. Create a class named weather report that holds a daily weather report
with data member day_of_month, hightemp, lowtemp, amount_rain and
amount_snow. The constructor initializes the fields with default values: 99
for day_of_month, 999 for hightemp,-999 for low emp and 0 for
amount_rain and amount_snow. Include a function that prompts the user
and sets values for each field so that you can override the default values.
Write a C++/Java/Python program that creates a monthly report. a) Menu
driven program with options to Enter data and Display report b) Report
Format
2. A book shop maintains the inventory of books that are being sold at the
shop. The list includes details such as author, title, price, publisher and
stock position. Whenever a customer wants a book, the sales person inputs
the title and author and the system searches the list and displays whether
it is available or not. If it is not, an appropriate message is displayed. If it
is, then the system displays the book details and requests for the number
of copies required. If the requested copies book details and requests for the
number of copies required. If the requested copies are available, the total
cost of the requested copies is displayed; otherwise the message “Required
copies not in stock” is displayed.Design a system using a class called
books with suitable member functions and Constructors. Use new
operator in constructors to allocate memory space required.Implement
C++ program for the system.
3. Develop an object oriented program in C++ to create a database of the
personnel information system containing the following information:
Name, Date of Birth, Blood group, Height, Weight, Insurance Policy,
number, Contact address, telephone number, driving license no. etc
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 3
Construct the database with suitable member functions for initializing and
destroying the data viz constructor, default constructor, copy, constructor,
destructor, static member functions, friend class, this pointer, inline code
and dynamic memory allocation operators-new and delete.
4. Design a C++ Class „Complex „ with data members for real and imaginary
part. Provide default and parameterized constructors. Write a program to
perform arithmetic operations of two complex numbers using operator
overloading (using either member functions or friend functions).
5. Write a C++ program to perform String operations
i. = Equality
ii. == String Copy
iii. + Concatenation
iv. << To display a string
v. >> To reverse a string
vi. Function to determine whether a string is a palindrome
To find occurrence of a sub-string. Use Operator Overloading.
6. Develop an object oriented program in C++ to create a database of the
personnel information system containing the following information:
Name, Date of Birth, Blood group, Height, Weight, Insurance Policy
number, Contact address, telephone number, driving licence no. etc
Construct the database with suitable member functions for initializing and
destroying the data viz constructor, default constructor, copy constructor,
destructor, static member functions , friend class, this pointer, inline code
and dynamic memory allocation operators-new and delete.
7. Write a program in C++ using function template to read two matrices of
different data types such as integers and floating point values and perform
simple arithmetic operations on these matrices separately and display it.
8. Design a C++ base class consisting of the data members such as name of
the student, roll number and subject. The derived class consists of the data
members subject code, internal assessment and university examination
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 4
marks. Construct a virtual base class for the item name of the student and
roll number. The program should have the facilities.
i) Build a master table ii) List a table iii) Insert a new entry
iv) Delete old entry v) Edit an entry vi) Search for a record
9. Create a C++ class named Television that has data members to hold the
model number and the screen size in inches, and the price. Member
functions include overloaded insertion and extraction operators. If more
than four digits are entered for the model, if the screen size is smaller than
12 or greater than 70 inches, or if the price is negative or over $5000 then
throw an integer. Write a main() function that instantiates a television
object, allows user to enter data and displays the data members .If an
exception is caught, replace all the data member values with zero values.
Group B
1. Implement C++/Java/Python program to create a base class called shape.
Use this class to store two double type values that could be used to
compute the area of figures. Derive two specific classes called function
get_data() to initialize base class data members and another member
function display_area() to compute and display the area of figures. Make
classes to suit their requirements. Using these three classes, design a
program that will accept dimension of a triangle or a rectangle
interactively, and display the area. Remember the two values given as
input will be treated as lengths of two sides in the case of rectangles, and
as base and height in the case of triangles, and used as follows:
Area of rectangle= x*y
Area of triangle =1/2*x*y
2. Implement C++/Java/Python program to implement a base class
consisting of the data members such as name of the student, roll number
and subject. The derived class consists of the data members subject code
,internal assessment and university examination marks. The program
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 5
should have the facilities. i) Build a master table ii) List a table iii) Insert a
new entry iv) Delete old entry v) Edit an entry vi) Search for a record. Use
virtual functions.
3. Implement C++/Java/Python program to write a class template to
represent a generic vector. Include following member functions:
To create the vector.
To modify the value of a given element
To multiply by a scalar value
To display the vector in the form (10,20,30,…)
4. Implement C++/Java/Python program for bubble sort using function
template
5. Write a C++/Java program for the following:
Create a class named Television that has data members to hold the model
number and the screen size in inches, and the price. Member functions
include overloaded insertion and extraction operators. If more than four
digits are entered for the model, if the screen size is smaller than 12 or
greater than 70 inches, or if the price is negative or over $5000 then throw
an exception. Write a main() function that instantiates a television object,
allows user to enter data and displays the data members .If an exception is
caught ,replace all the data member values with zero values.
Group C
1. Write a concurrent program to implement the Odd-Even Merge Sort.
Effective use of Multicore Architecture Core 1 and Core 2 effectively is
expected.
2. Write a concurrent program to implement the Dining philosopher‟s
problem. Effective use of Multicore Architecture is expected.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 6
GROUP A: ASSIGNMENTS
(All Mandatory)
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 7
Experiment No:1
Title: Monthly Weather Report using Constructor, Destructor.
Aim: Create a class named weather report that holds a daily weather
report with data members day_of_month, hightemp, lowtemp,
amount_rain and amount_snow. The constructor initializes the fields
with default values: 99 for day_of_month, 999 for hightemp,-999 for
low emp and 0 for amount_rain and amount_snow. Include a
function that prompts the user and sets values for each field so that
you can override the default values. Write a C++/Java/Python
program that creates a monthly report. a) Menu driven program
with options to Enter data and Display report b) Report Format
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn the concept of constructor and destructor in C++.
To study the representation, implementation and applications of data
structures
To study implementation of data structures using OOP concepts
To compare the benefits of static and dynamic data structures
Theory:
Constructor
A class constructor is a special member function of a class that is executed whenever
we create new objects of that class. A constructor will have exact same name as the
class and it does not have any return type at all, not even void. Constructors can be
very useful for setting initial values for certain member variables.
Why you should define a constructor?
Uninitialized member fields have garbage in them. This creates the possibility of a
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 8
serious bug (e.g., an uninitialized pointer, illegal values, inconsistent values ...).
Characteristics of a constructor:
1. They should be declared in the public section
2. They are invoked automatically when the objects are created.
3. They cannot be inherited
4. They cannot be virtual
A constructor is similar to a function, but with the following differences.
1. No return type.
2. No return statement.
Types of Constructor
1. Default Constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with default arguments
5. Dynamic constructor
Destructor
A destructor is a special member function of a class that is executed whenever an
object of its class goes out of scope or whenever the delete expression is applied to a
pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it
can neither return a value nor can it take any parameters. Destructor can be very
useful for releasing resources before coming out of the program like closing files,
releasing memories etc. Whenever the object of the class is created, the constructor is
called. Constructor is responsible for assigning initial values for all its data members.
It has the same name as its class. Whenever an object is no longer needed ,it has to be
deleted from the memory, then we write a destructor for it. It takes the same name of
their class preceded by a tilde (~)
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 9
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read day_of_month, hightemp, lowtemp, amount_rain and amount_snow.
3. Print report with all information.
4. Stop
Input:
i. High temperature
ii. Low temperature
iii. Amount of rain
iv. Amount of snow
Output:
Display report with high temperature, low temperature, amount of rain, amount of
snow. Display the result in following format:
hightemp lowtemp amount_rain amount_snow
1
2
.
.
.
28/30/31
--------------------------------------------------------------------
Average
Let S be the solution perspective of the class Weather Report such that
S={s, e, i, o, f, DD, NDD, success, failure}
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 10
s=initial state that is constructor of the class and e be the end state or destructor of the class.
i= input of the system.
o=output of the system.
DD-deterministic data it helps identifying the load store functions or assignment functions.
NDD- Non deterministic data of the system S to be solved.
Success-desired outcome generated.
Failure-Desired outcome not generated or forced exit due to system error.
For class Weather_Report:
s=initial state or constructor of the class weather()
s={weather()}- sets the default values for all five variables to respective values given in
assignment.
Input i=(I1,I2)
I1={day_of_moth,hightemp,lowtemp,amount_rain,amount_snow}
Variables declared-NDD
Day_of_month={1,-------,n} n≠Ø. n=30 or 31.
Hightemp={1,------,n} n≠Ø. n=999.
lowtemp={-999,------,n} n≠Ø. n=6.
amount_rain={1,------,n} n≠Ø. n=10.
amount_snow={1,------,n} n≠Ø. n=10.
I2={99,999,-999,0,0}
Default values set all integers –Deterministic Data because of function weather(),memory
requirement based on DD.
Hence let weather():I1I2 be an ONTO mapping function shown by fig
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 11
Draw Association figure here of mapping values of I1 to I2:
f= {display ( ), override ( ), avg ( )}
display ( )={details of all variable values}
override( )={ default values get overwritten and stored by values specified in this function}
avg( )={sum of values / no. of days}
Success- desired output is generated in tabular form as Weather Report with default as well as
overwritten values along with average.
Failure- desired output is not generated in tabular form as weather Report.
Conclusion:
Hence, we have successfully studied concept of constructor and destructor in object
oriented programming language.
Questions:
1. What is dynamic initialization of a variable?
2. Difference between a “assignment operator” and a “copy constructor”
3. What are the benefits of OOP?
4. Explain Destructor?
5. Explain copy constructor
6. Give example of a constructor with default values.
7. Give pictorial representation of object from your program.
Day
Hightemp
Lowtemp
Amount -rain
Amount-snow
99
999
-999
0
0
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 12
8. Memory allocation for static members.
9. Memory allocation for array of objects.
10. Difference between class variables and static variables
11. Pictorial representation of object from your program.
12. Explain types of constructor with example.
13. Uses of constructor
14. What is object and member function.
15. What is dynamic constructor .Explain with examples?
16. Difference between constructor and destructor.
Practice Assignments:
1. Create a class named STUDENT that holds student information Stdname,
StdRollno, Stdclass, Marks of subject, Percentage. The constructor
initializes the fields with default values. Include a function that prompts
the user and sets values for each field so that you can override the default
values. Write a program that creates a report for „N‟ number of students.
2. Create a class BANK that holds Account holder information Accname,
AccNo, Balance. The constructor initializes the fields with default values.
Include a function that prompts the user and sets values for each field so
that you can override the default values. Write a program that creates a
report for „N‟ number of Account Holder.
3. Create a class CRICKET that holds Name of Player, Century Scored, Runs
Scored, Average, Economy, Wickets, and Catches etc. The constructor
initializes the fields with default values. Include a function that prompts
the user and sets values for each field so that you can override the default
values. Write a program that creates a report for „N‟ number of Cricketers.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 13
Experiment No:2
Title: Book shop‟s inventory management using member functions and
constructors.
Aim: A book shop maintains the inventory of books that are being sold at
the shop. The list includes details such as author, title, price,
publisher and stock position. Whenever a customer wants a book,
the sales person inputs the title and author and the system searches
the list and displays whether it is available or not. If it is not, an
appropriate message is displayed. If it is, then the system displays
the book details and requests for the number of copies required. If
the requested copies book details and requests for the number of
copies required. If the requested copies are available, the total cost of
the requested copies is displayed; otherwise the message “Required
copies not in stock” is displayed. Design a system using a class called
books with suitable member functions and Constructors. Use new
operator in constructors to allocate memory space required.
Implement C++ program for the system.
Prerequisites:
Data Structures and problem Solving
Objectives:
To study the representation, implementation and applications of data
structures
To learn the concept of dynamic memory allocation and deallocation (use of
new and delete operator).
To compare the benefits of static and dynamic data structures
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 14
Theory:
The new and delete operators:
There is following generic syntax to use new operator to allocate memory
dynamically for any data-type.
new data-ty
Here, data-type could be any built-in data type including an array or any user
defined data types include class or structure. Let us start with built-in data types. For
example we can define a pointer to type double and then request that the memory be
allocated at execution time. We can do this using the new operator with the
following statements:
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had
been used up. So it is good practice to check if new operator is returning NULL
pointer and take appropriate action as below:
double* pvalue = NULL;
if( !(pvalue = new double ))
{
cout << "Error: out of memory." <<endl;
exit(1);
}
The malloc() function from C, still exists in C++, but it is recommended to
avoid using malloc() function. The main advantage of new over malloc() is that new
doesn't just allocate memory, it constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not
anymore required, you can free up the memory that it occupies in the free store with
the delete operator as follows:
delete pvalue; // Release memory pointed to by pvalue
Let us put above concepts and form the following example to show how new and delete
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 15
work:
#include <iostream>
using namespace std;
int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
If we compile and run above code, this would produce the following result:
Value of pvalue : 29495
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read book details such as author, title, price, publisher and stock position.
3. Print all information of book.
4. Stop
Input:
Details about books such as author, title, price, publisher and stock position
Output:
Display required book‟s details.
Conclusion:
Hence, we have successfully studied concept of new and delete operator.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 16
Questions:
1. What are new and delete?
2. What is dynamic allocation of a variable?
3. Difference between a “new” and a “delete”
4. Memory allocation for static members.
5. Memory allocation for array of objects.
6. Difference between class variables and static variables
7. Pictorial representation of object from your program.
8. What is object and member function.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 17
Experiment No:3
Title: Personnel information system using constructor, destructor, static
member functions, friend class, this pointer, inline code and dynamic
memory allocation.
Aim: Develop an object oriented program in C++ to create a database of
the personnel information system containing the following
information: Name, Date of Birth, Blood group, Height, Weight,
Insurance Policy, number, Contact address, telephone number,
driving license no. etc Construct the database with suitable member
functions for initializing and destroying the data viz constructor,
default constructor, copy, destructor, static member functions, friend
class, this pointer, inline code and dynamic memory allocation
operators-new and delete.
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn the concept of constructor, default constructor, copy, destructor, static
member functions, friend class, this pointer, inline code and dynamic memory
allocation operators-new and delete.
Theory:
A special method of the class that will be automatically invoked when an instance of
the class is created is called as constructor. Following are the most useful features of
constructor.
1) Constructor is used for Initializing the values to the data members of the
Class.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 18
2) Constructor is that whose name is same as name of class.
3) Constructor gets Automatically called when an object of class is created.
4) Constructors never have a Return Type even void.
5) Constructor is of Default, Parameterized and Copy Constructors.
The various types of Constructor are as follows:-
Constructors can be classified into 3 types
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
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 Remember name of Constructor is same as name of class and Constructor
never declared with the help of Return Type. Means we can‟t 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.
2. Parameterized Constructor: - This is another type constructor which has some
Arguments and same name as class name but it uses some Arguments So For this We
have to create object of Class by passing some Arguments at the time of creating
object with the name of class. When we pass some Arguments to the Constructor then
this will automatically pass the Arguments to the Constructor and the values will
retrieve by the Respective Data Members of the Class.
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 Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 19
Object to a Constructor then we must have to use the & Ampersand or Address
Operator.
Destructor: As we know that Constructor is that which is used for Assigning Some
Values to data Members and For Assigning Some Values this May also used Some
Memory so that to free up the Memory which is Allocated by Constructor, destructor
is used which gets Automatically Called at the End of Program and we doesn‟t have
to Explicitly Call a Destructor and Destructor Cant be Parameterized or a Copy This
can be only one Means Default Destructor which Have no Arguments. For Declaring
a Destructor we have to use ~tiled Symbol in front of Destructor.
Static members
A class can contain static members, either data or functions.
A static member variable has following properties:
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.
It is the visible only within the class but its lifetime is the entire program.
Static data members of a class are also known as "class variables", because there is
only one unique value for all the objects of that same class. Their content is not
different from one object static members have the same properties as global variables
but they enjoy class scope. For that reason, and to avoid them to be declared several
times, we can only include the prototype (its declaration) in the class declaration but
not its definition (its initialization). In order to initialize a static data-member we
must include a formal definition outside the class, in the global scope of this class to
another. Because it is a unique variable value for all the objects of the same class, it
can be referred to as a member of any object of that class or even directly by the class
name (of course this is only valid for static members.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 20
A static member function has following properties
A static function can have access to only other static members (fun or var)
declared in the same class
A static function can be called using the class name instead of its object name
Class_name :: fun_name;
Static member functions are considered to have class scope. In contrast to non static
member functions, these functions have no implicit this argument; therefore, they can
use only static data members, enumerators, or nested types directly. Static member
functions can be accessed without using an object of the corresponding class type.
The following restrictions apply to such static functions:
1. They cannot access non static class member data using the member-selection
operators (. or –>).
2. They cannot be declared as virtual.
3. They cannot have the same name as a non static function that has the same
argument types.
E.g. // static members in classes
class StaticTest {
private: static int x;
public: static int count()
{ return x;
}
};
int StaticTest::x = 9;
int main()
{
printf_s("%d\n", StaticTest::count());
}
Output
9
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 21
Friend functions:
In principle, private and protected members of a class cannot be accessed from
outside the same class in which they are declared. However, this rule does not affect
friends. Friends are functions or classes declared as such. If we want to declare an
external function as friend of a class, thus allowing this function to have access to the
private and protected members of this class, we do it by declaring a prototype of this
external function within the class, and preceding it with the keyword friend.
Properties of friend function:
It is not in the scope of the class to which it has been declared as friend.
Since it is not in the scope of the class , it cannot be called using the object of
that class
It can be invoked like a normal function w/o the help of any object.
It can be declared in private or in the public part of the class.
Unlike member functions, it cannot access the member names directly and has
to use an object name and dot operator with each member name.
// friend functions
#include <iostream>
using namespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area () {return (width * height);}
friend CRectangle duplicate (CRectangle);
};
void CRectangle::set_values (int a, int b) {
width = a;
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 22
height = b;
}
CRectangle duplicate (CRectangle rectparam)
{
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}
int main () {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}
The duplicate function is a friend of CRectangle. From within that function we have
been able to access the members width and height of different objects of type
CRectangle, which are private members. Notice that neither in the declaration of
duplicate() nor in its later use in main() have we considered duplicate a member of
class CRectangle.
Friend classes
Just as we have the possibility to define a friend function, we can also define a class as
friend of another one, granting that second class access to the protected and private
members of the first one.
// friend class
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 23
#include <iostream>
using namespace std;
class CSquare;
class CRectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side (int a)
{side=a;}
friend class CRectangle;
};
void CRectangle::convert (CSquare a) {
width = a.side;
height = a.side;
}
int main () {
CSquare sqr;
CRectangle rect;
sqr.set_side(4);
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 24
rect.convert(sqr);
cout << rect.area();
return 0;
}
In this example, we have declared CRectangle as a friend of CSquare so that
CRectangle member functions could have access to the protected and private
members of CSquare, more concretely to CSquare::side, which describes the side
width of the square..
Pointers:
A pointer is a derived data type that refers to another data variable by storing the
variables memory address rather than data.
Declaration of pointer variable is in the following form :
Eg int * ptr;
Here ptr is a pointer variable and points to an integer data type.
We can initialize pointer variable as follows
int a, *ptr; // declaration
ptr = &a //initialization
Pointers to objects:
Consider the following eg
item X; // where item is class and X is object
Similarly we can define a pointer it_ptr of type item as follows
Item *it_ptr ;
Object pointers are useful in creating objects at runtime. We can also access public
members of the class using pointers.
Eg item X;
item *ptr = &X;
Data_type * ptr_var;
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 25
the pointer „ptr „is initialized with address of X.
we can access the member functions and data using pointers as follows
ptr->getdata();
ptr->show();
this pointer:
C++ uses a unique keyword called this to represent an object that invokes a member
function. this is a pointer that points to the object for which this function was called.
This unique pointer is automatically passed to a member function when it is called.
Important notes on this pointer:
this pointer stores the address of the class instance, to enable pointer access of
the members to the member functions of the class.
this pointer is not counted for calculating the size of the object.
this pointers are not accessible for static member functions.
this pointers are not modifiable.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read personnel information such as Name, Date of Birth, Blood group, Height,
Weight, Insurance Policy, number, Contact address, telephone number,
driving license no..
3. Print all information from database.
4. Stop
Input:
Personnel information such as Name, Date of Birth, Blood group, Height, Weight,
Insurance Policy, number, Contact address, telephone number, driving license no.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 26
Output:
Display personnel information from database. The result in following format:
Name DOB ……. Driving License No
1
2
.
.
.
n
Conclusion:
Hence, we have successfully studied concept of constructor, default constructor, copy
constructor, destructor, static member functions, friend class, this pointer, inline code
and dynamic memory allocation operators-new and delete.
Questions:
1. What is static Function?
2. What is friend function? State the advantage of using the friend function.
3. What is friend class? Explain with examples.
4. Explain with examples pointers to object.
5. What is this pointer? Explain with examples.
6. State the advantages of this pointer.
7. What are inline functions?
8. How do we declare member of a class static?
9. What are demerits of friend function?
10. What is concept of constructor, destructor?
11. What are types of constructors?
Practice Assignments:
1. Develop an object oriented program in C++ to create a database of the
Student information system containing the following information: Name,
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 27
Date of Birth, Class, Marks, Contact address, telephone number, etc
Construct the database with suitable member functions for initializing and
destroying the data viz constructor, default constructor, copy constructor,
destructor, static member functions, friend class, this pointer, inline code
and dynamic memory allocation operators-new and delete.
2. Develop an object oriented program in C++ to create a database of the
Employee information system containing the following information: Name,
Date of Birth, Empcode, Contact address, telephone number, etc Construct
the database with suitable member functions for initializing and destroying
the data viz constructor, default constructor, copy constructor, destructor,
static member functions, friend function, this pointer, inline code and
dynamic memory allocation operators-new and delete.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 28
Experiment No: 4
Title: Complex numbers operator overloading
Aim: Design a C++ Class „Complex„ with data members for real and
imaginary part. Provide default and parameterized constructors.
Write a program to perform arithmetic operations of two complex
numbers using operator overloading (using either member functions
or friend functions).
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn the concept of constructor, default constructor, copy, constructor,
parameterized constructor‟s operator overloading using friend function.
Theory:
Operator Overloading
It is a specific case of polymorphism where different operators have different
implementations depending on their arguments.
In C++ the overloading principle applies not only to functions, but to operators too.
That is, of operators can be extended to work not just with built-in types but also
classes. A programmer can provide his or her own operator to a class by overloading
the built-in operator to perform some specific computation when the operator is used
on objects of that class.
An Example of Operator Overloading
Complex a(1.2,1.3); //this class is used to represent complex numbers
Complex b(2.1,3); //notice the construction taking 2 parameters for the real and imaginary
part
Complex c = a+b; //for this to work the addition operator must be overloaded
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 29
Arithmetic Operators
Arithmetic Operators are used to do basic arithmetic operations like addition,
subtraction, multiplication, division, and modulus.
The following table list the arithmetic operators used in C++.
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
With C++ feature to overload operators, we can design classes able to perform
operations using standard operators. Here is a list of all the operators that can be
overloaded:
Over loadable operators
+ - * / = < > += -= *= /= << >>
<<= >>= == != <= >= ++ -- % & ^ !
|
~ &= ^= |= && || %= []
To overload an operator in order to use it with classes we declare operator
functions, which are regular functions whose names are the operator keyword
followed by the operator sign that we want to overload. The format is:
type operator operator-symbol (parameters) {/*...*/ }
The operator keyword declares a function specifying what operator-symbol
means when applied to instances of a class. This gives the operator more than
one meaning, or "overloads" it. The compiler distinguishes between the
different meanings of an operator by examining the types of its operands.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 30
Algorithm:
1. Start
2. Read two complex numbers.
3. Perform arithmetic operations on two complex numbers
4. Print the output.
5. Stop
Input:
Complex numbers with real and imaginary values for two complex numbers.
Example :
Complex No 1: Real Part : 5
Imaginary part : 4
Complex No 2: Real Part : 5
Imaginary part : 4
Output:
Numbers after performing arithmetic operations in following format:
Operation Performed: Complex No: 1
Operation Symbol: Complex No: 2
-------------------------------------------------
RESULT
Conclusion:
Hence, we have studied concept of operator overloading.
Questions:
1. What is operator overloading?
2. What are the rules for overloading the operators?
3. State clearly which operators are overloaded and which operator are not
overloaded?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 31
4. State the need for overloading the operators.
5. Explain how the operators are overloaded using the friend function.
6. What is the difference between “overloading” and “overriding”?
7. What is operator function? Describe the syntax?
8. When is Friend function compulsory? Give an example?
9. How Many arguments required in the definition of an overloaded unary
operator?
Practice Assignments:
1. Design a Class Complex with data members for real and imaginary part.
Provide default and parameterized constructors. Write a program to perform
arithmetic operations of two complex numbers using operator overloading.
Overload << to accept two complex numbers
2. Design a Class Complex with data members for real and imaginary part.
Provide default and parameterized constructors. Write a program to perform
arithmetic operations of two complex numbers using operator overloading.
Overload >> to display output of the above performed operations on complex
numbers
3. Write a class to represent the vector (a series of float value). Include member
function to create a vector and to modify. Overload operator * to multiply by a
scalar value. Overload << to display scalar value.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 32
Experiment No: 5
Title: String operations operator overloading
Aim: Write a C++ program to perform String operations
i. = Equality
ii. == String Copy
iii. + Concatenation
iv. << To display a string
v. >> To reverse a string
vi. Function to determine whether a string is a palindrome
To find occurrence of a sub-strings. Use Operator Overloading.
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn the concept of operator overloading in terms of different string operations.
Theory:
Strings in C++:
Strings can be defines as class objects which can be then manipulated like a built in
data types. Since the strings vary greatly in size, we use „new‟ to allocate memory for
each string and a pointer variable to point to the string array. Thus we must create
string objects that can hold these two pieces of information, namely length and
location which are necessary for string manipulations. A typical string class will look
as
Class string {
Char *p;
Int len; // length of string
Public :
………….// mem fun to initialize and manipulate strings
…………..
};
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 33
Pointers are useful to allocate arrays dynamically i.e. we can decide the array size at
run time.
c++ incorporates the option to use standard operators to perform operations with
classes in addition to with fundamental types. For example:
int a, b,
c;
a = b + c;
This is obviously valid code in C++, since the different variables of the addition are
all fundamental types. Nevertheless, it is not so obvious that we could perform an
operation similar to the following one:
struct {
string
product;
float price;
} a, b, c;
a = b + c;
In fact, this will cause a compilation error, since we have not defined the behavior
our class should have with addition operations. However, thanks to the C++ feature
to overload operators, we can design classes able to perform operations using
standard operators.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read strings.
3. Perform String operations.
4. Print output.
5. Stop
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 34
Input:
Enter String1: Hello
Enter String2: World.
Output:
Display the result in following format:
Operation Performed: RESULTSTRING
Conclusion:
Hence, we have studied concept of operator overloading.
Questions:
1. Give the number of arguments for overloading unary and binary operator?
2. Which operators can‟t be overloaded?
3. Which operators can‟t be overloaded with friend functions?
4. What are inline functions?
5. Memory allocation for strings
Practice Assignments:
Write a C++ program to perform following operations on the strings.
1 > To Check two strings
2 + concatenation by friend functions
3 - To delete a substring
4 + concatenation using friend function
5 += To concat the two strings
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 35
Experiment No: 6
Title: Personnel information system using inheritance
Aim: Develop an object oriented program in C++ to create a database of
the personnel information system containing the following
information: Name, Date of Birth, Blood group, Height, Weight,
Insurance Policy number, Contact address, telephone number,
driving licence no. etc Construct the database with suitable member
functions for initializing and destroying the data viz constructor,
default constructor, copy constructor, destructor, static member
functions , friend class, this pointer, inline code and dynamic
memory allocation operators-new and delete.
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn concept of Inheritance, different types of inheritance: Single level, Multi
level, Multiple, Hybrid.
Theory:
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional features
to an existing class without modifying it. This is achieved by deriving a new class
from the existing one. The new class will have combined features of both the classes.
Types of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 36
5. Hybrid Inheritance
There are three types of class inheritance: public, private and protected
The protected access specifier is similar to private. Its only difference occurs in fact
with inheritance. When a class inherits from another one, the members of the derived
class can access the protected members inherited from the base class, but not its
private members.
Difference between public, private and protected
A member (either data member or member function) declared in a private
section of a class can only be accessed by member functions and friends of that
class
A member (either data member or member function) declared in a protected
section of a class can only be accessed by member functions and friends of that
class, and by member functions and friends of derived classes
A member (either data member or member function) declared in a public
section of a class can be accessed by anyone
The following table indicates how the attributes are inherited in the three different
types of inheritance:
Access specifier in the base class
private Public protected
public inheritance The member is
private.
The member is
public.
The member is
protected.
private
inheritance
The member is
private.
The member is
private.
The member is
private.
protected
inheritance
The member is
private.
The member is
protected.
The member is
protected.
What a derived class inherits
Every data member defined in the parent class (although such members¤ may
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 37
not always be accessible in the derived class!)
Every ordinary member function of the parent class (although such members¤
may not always be accessible in the derived class!)
The same initial data layout as the base class
What a derived class doesn't inherit
The base class's constructors and destructor
The base class's assignment operator
The base class's friends
What a derived class can add
New data members
New member functions
New constructors and destructor
New friends
Multiple inheritance
Allows you to create a derived class that inherits properties from more than one base
class. Because a derived class inherits members from all its base classes, ambiguities
can result. For example, if two base classes have a member with the same name, the
derived class cannot implicitly differentiate between the two members.
In the following example, classes A, B, and C are direct base classes for the derived
class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 38
1. Start
2. Read personnel information such as Name, Date of Birth, Blood group,
Height, Weight, Insurance Policy, number, Contact address, telephone
number, driving license no..
3. Print all information from database.
4. Stop
Input:
Three Base classes (B1, B2, and B3) which contains data members
1. name, date of birth, blood group
2. height and weight
3. insurance policy number and contact address
Create Derived class which consist data members telephone numbers and driving
license number
Output:
1. Display table containing all data Member
2. Insert a new entry
2. Delete entry
3. Edit entry
4. Search for a record
Conclusion:
Hence, we have successfully studied concept of inheritance.
Questions:
1. What are the different forms of inheritance?
2. When do we use protected access specifier?
3. How does containership differ from inheritance?
4. What are Virtual Functions? How to implement virtual functions in “C”
5. Explain protected mode
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 39
6. Diagram of multiple inheritance
7. What's the difference between public, private, and protected?
8. Pictorial representation of object from your program
Practice Assignments:
1. Design a base class with Employee name, date of birth, blood group and
another base class consisting of the data members such as designation and
salary. Design one more base class consisting of the insurance policy
number and contact address. The derived class contains the data member
telephone numbers and driving license number. Write a menu driven
program to carry out the following things:
Build a master table
Display
Insert a new entry
Delete entry
Edit
Search for a record
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 40
Experiment No: 7
Title: Templates
Aim: Write a program in C++ using function template to read two matrices
of different data types such as integers and floating point values and
perform simple arithmetic operations on these matrices separately and
display it.
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand concept of Template and Template function.
Theory:
C++ templates provide a way to re-use source code. C++ provides two kinds of
templates:
1. Class templates
2. Function templates.
Use function templates to write generic functions that can be used with arbitrary types.
For example, one can write searching and sorting routines which can be used with any
arbitrary type.C++ Function templates are those functions which can handle different
data types without separate code for each of them. For a similar operation on several
kinds of data types, a programmer need not write different versions by overloading a
function. It is enough if he writes a C++ template based function. This will take care of
all the data types.
Class Templates
A class template definition looks like a regular class definition, except it is prefixed by
the keyword template. Once code is written as a C++ class template, it can support all
data types.
Declaration of C++ class template should start with the keyword template. A parameter
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 41
should be included inside angular brackets. The parameter inside the angular brackets,
can be either the keyword class or typename. This is followed by the class body
declaration with the member data and member functions.
.
T is a type parameter and it can be any type. Defining member functions - C++ Class
Templates:
If the functions are defined outside the template class body, they should always be
defined with the full template definition. Other conventions of writing the function in
C++ class templates are the same as writing normal c++ functions.
Advantages of C++ Class Templates:
One C++ Class Template can handle different types of parameters.
Compiler generates classes for only the used types. If the template is instantiated
for int type, compiler generates only an int version for the c++ template class.
Templates reduce the effort on coding for different data types to a single set of
code.
Testing and debugging efforts are reduced.
Function templates
There are lot of occasions, where we might need to write the same functions for
different data types. A favorite example can be addition of two variables. The variable
can be integer, float or double. The requirement will be to return the corresponding
return type based on the input type. If we start writing one function for each of the
data type, then we will end up with 4 to 5 different functions, which can be a night
mare for maintenance.
template <class T>
class class_name
{
// class member specification
// with anonymous type T wherever appropriate
};
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 42
C++ templates come to our rescue in such situations. When we use C++ function
templates, only one function signature needs to be created. The C++ compiler will
automatically generate the required functions for handling the individual data types.
Eg: Add function.
Template <class T>
T Add(T a, T b)
{
Return a+b;
}
This c++ function template definition will be enough. Now when the integer version of
the function, the compiler generates an Add function compatible for integer data type
and if float is called it generates float type and so on. Here T is the typename. This is
dynamically determined by the compiler according to the parameter passed. The
keyword class means, the parameter can be of any type. It can even be a class.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read two matrices of different data types such as integers and floating point
values.
3. Perform simple arithmetic operations on these matrices separately.
4. Display output.
5. Stop
Input:
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 43
Output:
2 2 2
2 2 2
2 2 2
Conclusion:
Hence, we have successfully studied concept of Template and function template.
Questions:
1. Distinguish between overloaded functions and function templates?
2. What is the difference between macro and template?
3. What is the use of class template?
4. What is the difference between class template & function template?
5. What do you mean by a class template instantiation?
6. Can we use static data members in class template?
7. How to define a member function outside of its template?
8. How to define and declare the function template?
9. List the advantages & disadvantages of function template.
10. Can we overload the function template?
Practice Assignments:
1. Write C++ programs to create a template class QUEUE with add and delete
member functions. Using it, implement a queue of integers and doubles.
2. Write a program to create a class template LINKED LIST with insert & delete
operations. Using it, implement singly linked list of integer & floating point
values.
3. Write a program to define and declare a function template to fine “ a to the
power of b” with a and b taking int , float and double values.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 44
Experiment No: 8
Title: Virtual functions and files
Aim: Design a C++ base class consisting of the data members such as
name of the student, roll number and subject. The derived class
consists of the data member‟s subject code, internal assessment and
university examination marks. Construct a virtual base class for the
item name of the student and roll number. The program should have
the facilities.
i) Build a master table ii) List a table iii) Insert a new entry
iv) Delete old entry v) Edit an entry vi) Search for a record
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand how to perform various operations on files.
To understand the concept of Virtual Function
Theory:
C++ Virtual Function - Properties:
1. A member function of a class
2. Declared with virtual keyword
3. Usually has a different functionality in the derived class
4. A function call is resolved at run-time
The difference between a non-virtual c++ member function and a virtual member
function is, the non-virtual member functions are resolved at compile time. This
mechanism is called static binding. Whereas the c++ virtual member functions are
resolved during run-time. This mechanism is known as dynamic binding.
C++ Virtual Function - Reasons:
The most prominent reason why a C++ virtual function will be used is to have a
different functionality in the derived class.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 45
Rules for virtual functions:
When virtual functions are created for implementing late binding, we should observe
some basic rules that satisfy the compiler requirements.
1. The virtual functions must be member of the same class
2. They cannot be static members
3. They are accessed by using object pointers
4. A virtual function can be a friend of another class.
Input/output with files
C++ provides the following classes to perform output and input of characters
to/from files:
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the classes istream, and ostream.
We have already used objects whose types were these classes: cin is an object of class
istream and cout is an object of class ostream. Therefore, we have already been using
classes that are related to our file streams. And in fact, we can use our file streams the
same way we are already used to use cin and cout, with the only difference that we
have to associate these streams with physical files
Opening files using open()
The function open () can be used to open multiple files that use same stream object .
Eg fstream inoutfile;
Inoutfile.open(“book.dat”);
Where filename is a null-terminated character sequence of type const char * (the
same type that string literals have) representing the name of the file to be opened,
and mode is an optional parameter with a combination of the following flags:
File_stream_class stream _object;
Stream_object .open (―filename‖, mode);
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 46
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate
Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning
of the file.
ios::app
All output operations are performed at the end of the file, appending
the content to the current content of the file. This flag can only be used
in streams open for output-only operations.
ios::trunc If the file opened for output operations already existed before, its
previous content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we
want to open the file example.bin in binary mode to add data we could do it by the
following call to member function open():
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app |
ios::binary);
For ifstream and ofstream classes, ios::in and ios::out are automatically and
respectivelly assumed, even if a mode that does not include them is passed as second
argument to the open() member function. The default value is only applied if the
function is called without specifying any value for the mode parameter. If the
function is called with any value in that parameter the default mode is overridden,
not combined.
File streams opened in binary mode perform input and output operations
independently of any format considerations. Non-binary files are known as text files,
and some translations may occur due to formatting of some special characters (like
newline and carriage return characters).
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 47
Since the first task that is performed on a file stream object is generally to open a file,
these three classes include a constructor that automatically calls the open() member
functions and has the exact same parameters as this member. Therefore, we could
also have declared the previous myfile object and conducted the same opening
operation in our previous example by writing:
ofstream myfile ("example.bin", ios::out | ios::app |
ios::binary);
Combining object construction and stream opening in a single statement. Both forms
to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to
member is_open() with no arguments. This member function returns a bool value of
true in the case that indeed the stream object is associated with an open file, or false
otherwise:
if (myfile.is_open()) { /* ok, proceed with
output */ }
Closing a file
When we are finished with our input and output operations on a file we shall close it
so that its resources become available again. In order to do that we have to call the
stream's member function close(). This member function takes no parameters, and
what it does is to flush the associated buffers and close the file:
myfile.close(
);
Once this member function is called, the stream object can be used to open another
file, and the file is available again to be opened by other processes.
Checking state flags
eof() Returns true if a file open for reading has reached the end.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 48
Functions for manipulation of file pointers :
All the actions on the file pointers take place automatically by default. The file
stream classes support following functions to manage file pointers manually.
tellg() and tellp()
These two member functions have no parameters and return a value of the member
type pos_type, which is an integer data type representing the current position of the
get stream pointer (in the case of tellg) or the put stream pointer (in the case of tellp).
seekg() and seekp()
These functions allow us to change the position of the get and put stream pointers.
Both functions are overloaded with two different prototypes. The first prototype is:
seekg ( position );
seekp ( position );
Using this prototype the stream pointer is changed to the absolute position position
(counting from the beginning of the file). The type for this parameter is the same as
the one returned by functions tellg and tellp: the member type pos_type, which is an
integer value.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read data members such as name of the student, roll number and subject.
3. Perform operations.
4. Print Output
5. Stop
Input:
Enter the students Details- Name, Age etc
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 49
Output:
1. Master table containing all data Member
2. Display
3. Insert a new entry
4. Delete entry
5. Edit
6. Search for a record
Conclusion:
Hence, we have successfully studied concept of Template and function template.
Questions:
1. What is a virtual function?
2. When do we make a virtual function pure?
3. What is virtual base class?
4. What is an abstract class?
5. What are two different ways to open the file?
6. Explain seekg(), seekp(), tellg(), tellp();
7. Differentiate between „ate‟ mode and „app‟ mode.
8. Explain the technique of static and dynamic binding
Practice Assignments:
1. Write a C++ program to generate Fibonacci series of n numbers using run time
binding. The series initials are 0 and 1.
2. Write a C++ program to print the factorial of a given number using dynamic
binding.
3. Write a C++ program to maintain the employee record using file handling.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 50
Experiment No: 9
Title: Exception Handling
Aim: Create a C++ class named Television that has data members to hold
the model number and the screen size in inches, and the price.
Member functions include overloaded insertion and extraction
operators. If more than four digits are entered for the model, if the
screen size is smaller than 12 or greater than 70 inches, or if the
price is negative or over $5000 then throw an integer. Write a
main() function that instantiates a television object, allows user to
enter data and displays the data members .If an exception is caught,
replace all the data member values with zero values.
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand the concept of Exception handling
Theory:
One benefit of C++ over C is its exception handling system. An exception is a
situation in which a program has an unexpected circumstance that the section of
code containing the problem is not explicitly designed to handle. In C++, exception
handling is useful because it makes it easy to separate the error handling code from
the code written to handle the chores of the program. Doing so makes reading and
writing the code easier. Furthermore, exception handling in C++ propagates the
exceptions up the stack; therefore, if there are several functions called, but only one
function that needs to reliably deal with errors, the method C++ uses to handle
exceptions means that it can easily handle those exceptions without any code in the
intermediate functions. One consequence is that functions don't need to return error
codes, freeing their return values for program logic.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 51
When errors occur, the function generating the error can 'throw' an exception. For
example, take a sample function that does division:
const int DivideByZero = 10;
//....
double divide(double x, double y)
{
if(y==0)
{
throw DivideByZero;
}
return x/y;
}
The function will throw DivideByZero as an exception that can then be caught by an
exception-handling catch statement that catches exceptions of type int. The
necessary construction for catching exceptions is a try catch system. If you wish to
have your program check for exceptions, you must enclose the code that may have
exceptions thrown in a try block. For example:
try
{
divide(10, 0);
}
catch(int i)
{
if(i==DivideByZero)
{
cerr<<"Divide by zero error";
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 52
The catch statement catches exceptions that are of the proper type. You can, for
example, throw objects of a class to differentiate between several different
exceptions. It is often more useful for you to create a class that stores information on
exceptions as they occur. For example, it would be more useful if you had a class to
handle exceptions.
class DivideByZero
{
public:
double divisor;
DivideByZero(double x);
};
DivideByZero::DivideByZero(double x) : divisor(x)
{}
int divide(int x, int y)
{
if(y==0)
{
throw DivideByZero(x);
}
}
try
{
divide (12, 0);
}
catch (DivideByZero divZero)
{
cerr<<"Attempted to divide "<<divZero.divisor<<" by zero";
}
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 53
If you wish to catch more than one possible exception, you can specify separate
catch blocks for each type of exception. It's also possible to have a general exception
handler that will respond to any thrown exception. To use it, simply use catch (...)
for the catch statement and print a general warning of some kind.
The handy thing to remember about exception handling is that the errors can be
handled outside of the regular code. This means that it is easier to structure the
program code, and it makes dealing with errors more centralized. .
In C, you might see some error handling code to free memory and close files
repeated five or or six times, once for each possible error. A solution some
programmer‟s preferred was to use a goto statement that jumped all the way to the
cleanup code. Now, you can just surround your code with a try-catch block and
handle any cleanup following the catch (possibly with an additional copy of your
cleanup routine inside the catch block if you intend to throw the exception again to
alert the calling function of an error).
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read television details such as model number, screen size in inches and the
price.
3. Print data members.
4. Stop
Input:
Class Television
Data members: model number, screen size , price
Member functions:
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 54
Overloaded Insertion and Extraction operators.
Get data, Display data.
Output:
If exception is caught display error message.
Conclusion:
Hence, we have successfully studied concept of exception handling.
Questions:
1. How exception is handled in c++?
2. When should a program throw exception?
3. When do we use multiple catch handlers?
Practice Assignments:
1. Perform Division by zero exceptional handling?
2. Perform Array Index out of range exceptional handling?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 55
GROUP B: ASSIGNMENTS
(Any Two)
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 56
Experiment No: 1
Title: Area of rectangle and triangle using inheritance.
Aim: Implement C++/Java/Python program to create a base class called
shape. Use this class to store two double type values that could be
used to compute the area of figures. Derive two specific classes
called function get_data() to initialize base class data members and
another member function display_area() to compute and display
the area of figures. Make classes to suit their requirements. Using
these three classes, design a program that will accept dimension of
a triangle or a rectangle interactively, and display the area.
Remember the two values given as input will be treated as lengths
of two sides in the case of rectangles, and as base and height in the
case of triangles, and used as follows:
Area of rectangle= x*y
Area of triangle =1/2*x*y
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn the concept of inheritance.
To study the representation, implementation and applications of data
structures
To study implementation of data structures using OOP concepts
Theory:
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional
features to an existing class without modifying it. This is achieved by deriving a
new class from the existing one. The new class will have combined features of both
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 57
the classes.
Types of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance
There are three types of class inheritance: public, private and protected
The protected access specifier is similar to private. Its only difference occurs in fact
with inheritance. When a class inherits from another one, the members of the
derived class can access the protected members inherited from the base class, but
not its private members.
What a derived class inherits
Every data member defined in the parent class (although such members¤
may not always be accessible in the derived class!)
Every ordinary member function of the parent class (although such
members¤ may not always be accessible in the derived class!)
The same initial data layout as the base class
What a derived class doesn't inherit
The base class's constructors and destructor
The base class's assignment operator
The base class's friends
What a derived class can add
New data members
New member functions
New constructors and destructor
New friends
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 58
E.g. Suppose that we want to declare a series of classes that describe polygons like
our CRectangle, or like CTriangle. They have certain common properties, such as
both can be described by means of only two sides: height and base. This could be
represented in the world of classes with a class CPolygon from which we would
derive the two other ones: CRectangle and CTriangle.
The class CPolygon would contain members that are common for both types of
polygon. In our case: width and height. And CRectangle and CTriangle would be its
derived classes, with specific features that are different from one type of polygon to
the other.
Classes that are derived from others inherit all the accessible members of the base
class. That means that if a base class includes a member A and we derive it to
another class with another member called B, the derived class will contain both
members A and B.
In order to derive a class from another, we use a colon (:) in the declaration of the
derived class using the following format:
Class derived_class_name: public base_class_name
{ /*...*/ };
Where derived_class_name is the name of the derived class and base_class_name is
the name of the class on which it is based. The public access specifier may be
replaced by any one of the other access specifiers protected and private. This access
specifier describes the minimum access level for the members that are inherited
from the base class.
// derived classes
#include <iostream>
using namespace std;
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 59
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
The objects of the classes CRectangle and CTriangle each contain members inherited
from CPolygon. These are: width, height and set_values().
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 60
Multiple inheritance
Allows you to create a derived class that inherits properties from more than one
base class. Because a derived class inherits members from all its base classes,
ambiguities can result. For example, if two base classes have a member with the
same name, the derived class cannot implicitly differentiate between the two
members.
In the following example, classes A, B, and C are direct base classes for the derived
class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read the values as length of two sides.
3. Print output.
4. Stop
Input:
Length of base and height.
Output:
Area of rectangle.
Conclusion:
Hence, we have successfully implemented class shape, to calculate the area of
rectangle.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 61
Questions:
1. What are the different forms of inheritance?
2. When do we use protected access specifier?
3. What are Virtual Functions? How to implement virtual functions in “C”
4. Explain protected mode.
5. Diagram of multiple inheritance
6. What's the difference between public, private, and protected?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 62
Experiment No: 2
Title: Bubble sort using function template.
Aim: Implement C++/Java/Python program for bubble sort using
function template
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand the concept of function template.
Theory:
Function templates
Function templates are special functions that can operate with generic types. This
allows us to create a function template whose functionality can be adapted to more
than one type or class without repeating the entire code for each type. In C++ this
can be achieved using template parameters. A template parameter is a special kind of
parameter that can be used to pass a type as argument: just like regular function
parameters can be used to pass values to a function, template parameters allow to
pass also types to a function. These function templates can use these parameters as
if they were any other regular type. The format for declaring function templates
with type parameters is:
template<classidentifier>function_declaration;
template<typenameidentifier>function_declaration;
For example, to create a template function that returns the greater one of two objects
we could use:
1
2
template <class myType>
myType GetMax (myType a, myType
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 63
3
4
b) {
return (a>b?a:b);
}
Here we have created a template function with myType as its template parameter.
This template parameter represents a type that has not yet been specified, but that
can be used in the template function as if it were a regular type. As you can see, the
function template GetMax returns the greater of two parameters of this still-
undefined type.
Template is a powerful feature of Object oriented programming. They give the
flexibility to a programmer for using any data type in a function without rewriting
the whole boring function for each data type again and again.
Here in this program we have written a function for Bubble sort and we have added
a template tag before the function so that, the parameter will be of the data type
Name. Everything is same except some variable data types. Take a look at the below
program, you‟ll get a clear idea.
In the main function we are passing some predefined values into the bubble
function by calling the function bubble(a,6) where a is the array containing integers
and 6 is the size of array. After passing the values into the function we are
displaying the sorted order. You can also rewrite the main function in a way that
the user will enter the data and size of the array.
Bubble sort
The simplest sorting algorithm is bubble sort. The bubble sort works by iterating
down an array to be sorted from the first element to the last, comparing each pair of
elements and switching their positions if necessary. This process is repeated as
many times as necessary, until the array is sorted. Since the worst case scenario is
that the array is in reverse order, and that the first element in sorted array is the last
element in the starting array, the most exchanges that will be necessary is equal to
the length of the array.
Here is a simple example: Given an array 23154 a bubble sort would lead to the
following sequence of partially sorted arrays:
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 64
21354, 21345, 12345. First the 1 and 3 would be compared and switched, then the 4
and 5. On the next pass, the 1 and 2 would switch, and the array would be in order.
The basic code for bubble sort looks like this, for sorting an integer array:
for(int x=0; x<n; x++)
{
for(int y=0; y<n-1; y++)
{
if(array[y]>array[y+1])
{
int temp = array[y+1];
array[y+1] = array[y];
array[y] = temp;
}
}
}
Notice that this will always loop n times from 0 to n, so the order of this algorithm
is O(n^2). This is both the best and worst case scenario because the code contains no
way of determining if the array is already in order. A better version of bubble sort,
known as modified bubble sort, includes a flag that is set if an exchange is made
after an entire pass over the array. If no exchange is made, then it should be clear
that the array is already in order because no two elements need to be switched. In
that case, the sort should end. The new best case order for this algorithm is O(n), as
if the array is already sorted, then no exchanges are made. You can figure out the
code yourself! It only requires a few changes to the original bubble sort.
Algorithm Bubble Sort:
Bubble(A, N)
//Let A be an array with N elements.
//This algorithm sorts the elements in array A.
Repeat for I = 0 to N:
Repeat for J = 0 to N-1:
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 65
If A[J] > A[J + 1], then Interchange A[J] & A[J +1].
End for
End for.
End Bubble Sort
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read the numbers as integers or characters.
3. Sort them according to ascending order.
4. Print values as output.
5. Stop
Input:
Integer values, Character values.
Output:
Sorted order of integers as well as characters.
Conclusion:
Hence, we have successfully implemented bubble sort using function template
Questions:
1. What is template?
2. What is function template?
3. How to sort elements using bubble sort?
4. What is Complexity of bubble sort?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 66
Experiment No: 3
Title: Exception Handling
Aim: Create a C++ class named Television that has data members to hold
the model number and the screen size in inches, and the price.
Member functions include overloaded insertion and extraction
operators. If more than four digits are entered for the model, if the
screen size is smaller than 12 or greater than 70 inches, or if the
price is negative or over $5000 then throw an integer. Write a
main() function that instantiates a television object, allows user to
enter data and displays the data members .If an exception is caught,
replace all the data member values with zero values.
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand the concept of Exception handling.
Theory:
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 67
One benefit of C++ over C is its exception handling system. An exception is a
situation in which a program has an unexpected circumstance that the section of
code containing the problem is not explicitly designed to handle. In C++, exception
handling is useful because it makes it easy to separate the error handling code from
the code written to handle the chores of the program. Doing so makes reading and
writing the code easier. Furthermore, exception handling in C++ propagates the
exceptions up the stack; therefore, if there are several functions called, but only one
function that needs to reliably deal with errors, the method C++ uses to handle
exceptions means that it can easily handle those exceptions without any code in the
intermediate functions. One consequence is that functions don't need to return error
codes, freeing their return values for program logic.
When errors occur, the function generating the error can 'throw' an exception. For
example, take a sample function that does division:
const int DivideByZero = 10;
//....
double divide(double x, double y)
{
if(y==0)
{
throw DivideByZero;
}
return x/y;
}
The function will throw DivideByZero as an exception that can then be caught by an
exception-handling catch statement that catches exceptions of type int. The
necessary construction for catching exceptions is a try catch system. If you wish to
have your program check for exceptions, you must enclose the code that may have
exceptions thrown in a try block. For example:
try
{
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 68
divide(10, 0);
}
catch(int i)
{
if(i==DivideByZero)
{
cerr<<"Divide by zero error";
}
}
The catch statement catches exceptions that are of the proper type. You can, for
example, throw objects of a class to differentiate between several different
exceptions. It is often more useful for you to create a class that stores information on
exceptions as they occur. For example, it would be more useful if you had a class to
handle exceptions.
If you wish to catch more than one possible exception, you can specify separate
catch blocks for each type of exception. It's also possible to have a general exception
handler that will respond to any thrown exception. To use it, simply use catch (...)
for the catch statement and print a general warning of some kind.
The handy thing to remember about exception handling is that the errors can be
handled outside of the regular code. This means that it is easier to structure the
program code, and it makes dealing with errors more centralized. .
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read television details such as model number, screen size in inches and
the price.
3. Print data members.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 69
4. Stop
Input:
1. Class Television
2. Data members: model number, screen size , price
3. Member functions:
4. Overloaded Insertion and Extraction operators.
5. Get data, Display data.
Output:
If exception is caught display error message.
Conclusion:
Hence, we have successfully studied concept of exception handling.
Questions:
1. How exception is handled in c++?
2. When should a program throw exception?
3. When do we use multiple catch handlers?
Practice Assignments:
1. Perform Division by zero exceptional handling?
2. Perform Array Index out of range exceptional handling?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 70
Experiment No: 4
Title: Employee bio-data using inheritance
Aim: Create employee bio-data using following classes: i) Personal record ii)
Professional record iii) Academic record Assume appropriate data members
and member function to accept required data & print bio-data. Create bio-
data using multiple inheritance using C++/Java/Python.
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn concept of Inheritance.
Theory:
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional features
to an existing class without modifying it. This is achieved by deriving a new class
from the existing one. The new class will have combined features of both the classes.
Types of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance
There are three types of class inheritance: public, private and protected
The protected access specifier is similar to private. Its only difference occurs in fact
with inheritance. When a class inherits from another one, the members of the derived
class can access the protected members inherited from the base class, but not its
private members.
Difference between public, private and protected
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 71
A member (either data member or member function) declared in a private
section of a class can only be accessed by member functions and friends of that
class
A member (either data member or member function) declared in a protected
section of a class can only be accessed by member functions and friends of that
class, and by member functions and friends of derived classes
A member (either data member or member function) declared in a public
section of a class can be accessed by anyone
The following table indicates how the attributes are inherited in the three different
types of inheritance:
Access specifier in the base class
Private Public protected
public inheritance The member is
private.
The member is
public.
The member is
protected.
private
inheritance
The member is
private.
The member is
private.
The member is
private.
protected
inheritance
The member is
private.
The member is
protected.
The member is
protected.
What a derived class inherits
Every data member defined in the parent class (although such members¤ may
not always be accessible in the derived class!)
Every ordinary member function of the parent class (although such members¤
may not always be accessible in the derived class!)
The same initial data layout as the base class
What a derived class doesn't inherit
The base class's constructors and destructor
The base class's assignment operator
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 72
The base class's friends
What a derived class can add
New data members
New member functions
New constructors and destructor
New friends
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
1. Start
2. Read employee information i.e. personal, professional academic.
3. Print all information from database.
4. Stop
Input:
Base class which consist data members name of employee, qualification and etc.
Three derived classes (B1, B2, and B3) which contains data members relevant to
personal, professional and academic details.
Output:
1. Display table containing all data Member
2. Insert a new entry
Conclusion:
Hence, we have successfully studied concept of inheritance.
Questions:
1. What are the different forms of inheritance?
2. When do we use protected access specifier?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 73
3. How does containership differ from inheritance?
4. What are Virtual Functions? How to implement virtual functions in “C”
5. Explain protected mode
6. Diagram of multiple inheritance
7. What's the difference between public, private, and protected?
8. Pictorial representation of object from your program
Practice Assignments:
1. Design a base class with Employee name, date of birth, blood group
and another base class consisting of the data members such as
designation and salary. Design one more base class consisting of the
insurance policy number and contact address. The derived class
contains the data member telephone numbers and driving license
number. Write a menu driven program to carry out the following
things:
Build a master table
Display
Insert a new entry
Delete entry
Edit
Search for a record
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 74
Experiment No: 4
Title: Employee bio-data using inheritance
Aim: Create employee bio-data using following classes: i) Personal record ii)
Professional record iii) Academic record Assume appropriate data members
and member function to accept required data & print bio-data. Create bio-
data using multiple inheritance using C++/Java/Python.
Prerequisites:
Data Structures and problem Solving
Objectives:
To learn concept of Inheritance.
Theory:
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional features
to an existing class without modifying it. This is achieved by deriving a new class
from the existing one. The new class will have combined features of both the classes.
Types of Inheritance
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid Inheritance
There are three types of class inheritance: public, private and protected
The protected access specifier is similar to private. Its only difference occurs in fact
with inheritance. When a class inherits from another one, the members of the derived
class can access the protected members inherited from the base class, but not its
private members.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 75
Difference between public, private and protected
A member (either data member or member function) declared in a private
section of a class can only be accessed by member functions and friends of that
class
A member (either data member or member function) declared in a protected
section of a class can only be accessed by member functions and friends of that
class, and by member functions and friends of derived classes
A member (either data member or member function) declared in a public
section of a class can be accessed by anyone
The following table indicates how the attributes are inherited in the three different
types of inheritance:
Access specifier in the base class
Private Public protected
public inheritance The member is
private.
The member is
public.
The member is
protected.
private
inheritance
The member is
private.
The member is
private.
The member is
private.
protected
inheritance
The member is
private.
The member is
protected.
The member is
protected.
What a derived class inherits
Every data member defined in the parent class (although such members¤ may
not always be accessible in the derived class!)
Every ordinary member function of the parent class (although such members¤
may not always be accessible in the derived class!)
The same initial data layout as the base class
What a derived class doesn't inherit
The base class's constructors and destructor
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 76
The base class's assignment operator
The base class's friends
What a derived class can add
New data members
New member functions
New constructors and destructor
New friends
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
5. Start
6. Read employee information i.e. personal, professional academic.
7. Print all information from database.
8. Stop
Input:
Base class which consist data members name of employee, qualification and etc.
Three derived classes (B1, B2, and B3) which contains data members relevant to
personal, professional and academic details.
Output:
3. Display table containing all data Member
4. Insert a new entry
Conclusion:
Hence, we have successfully studied concept of inheritance.
Questions:
1. What are the different forms of inheritance?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 77
2. When do we use protected access specifier?
3. How does containership differ from inheritance?
4. What are Virtual Functions? How to implement virtual functions in “C”
5. Explain protected mode
6. Diagram of multiple inheritance
7. What's the difference between public, private, and protected?
8. Pictorial representation of object from your program
Practice Assignments:
1. Design a base class with Employee name, date of birth, blood group
and another base class consisting of the data members such as
designation and salary. Design one more base class consisting of the
insurance policy number and contact address. The derived class
contains the data member telephone numbers and driving license
number. Write a menu driven program to carry out the following
things:
Build a master table
Display
Insert a new entry
Delete entry
Edit
Search for a record
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 78
Experiment No: 5
Title: POSIX-spawn() function to create a process
Aim: Using multi-core programming implement POSIX-spawn() function to
create a process
Prerequisites:
Basic Concepts on Multicore Programming and Data Structures and problem
SolvingConcepts.
Objectives:
To learn concept of Process Creation using posix_spwan() function.
Theory:
Portable Operating System Interface (POSIX) is a standard that defines a standard operating
system interface and environment, including a command interpreter (or ― shell ‖ ) and
common utility programs to support applications portability at the source code level. The
standard is intended be used by both applications developers and system implementors. To
make this book accessible to the broadest possible audience of system and application
developers we choose to present OS API material using the POSIX standard. The major
operating system environments — ZOS, Solaris, AIX, Windows, Mac OS X, Linux, HP -UX,
IRIX — all claim basic support for the POSIX standard. While each of these environments
has its own proprietary APIs, each also has support for the POSIX standard. Since the
concepts, examples, and programs we discuss are based on the POSIX standard, you can try
them out in virtually any environment. The POSIX standard plays the role of a cross -
platform pseudocode that allows us to cover the main concepts of multicore programming in a
language that can be implemented in all of the major environments. Further, POSIX
implements a kind of ― common denominator ‖ OS interface.
Using posix_spawn()
Similarly to the fork - exec() and system() methods of process creation, the posix_spawn()
functions create new child processes from specified process images. But the posix_spawn()
functions create child processes with more fine - grained control during creation. While the
POSIX API also supports the fork - exec() class of functions, we focus on the posix_spawn
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 79
functions for process creation to achieve greater cross - platform compatibility. Some
platforms may have trouble implementing fork() , so the posix_spawn() functions can be used
as substitution. These functions control the attributes that the child process inherits from the
parent process, including:
File descriptors
Scheduling policy
Process group id
User and group id
Signal mask
Synopsis
#include < spawn.h >
int posix_spawn(pid_t *restrict pid, const char *restrict path, const
posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict
attrp, char *const argv[restrict], char *const envp[restrict]);
int posix_spawnp(pid_t *restrict pid, const char *restrict file, const
posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 80
attrp, char *const argv[restrict],
char *const envp[restrict]);
The difference between these two functions is that posix_spawn() has a path parameter and
posix_spawnp() has a file parameter. The path parameter in the posix_spawn() function is the
absolute or relative pathname to the executable program file. file in posix_spawnp() is the
name of the executable program. If the parameter contains a slash, then file is used as a
pathname. If not, the path to the executable is determined by PATH environment variable.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Input:
Process Id, Path, Process State, Process Priority and process environment variable.
Output:
New Process with Id.
Conclusion:
posix_spawn() is used to create new process.
Questions:
1. What is posix_spawn() function?
2. What syntax of posix_spawn() function?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 81
Experiment No: 6
Title: Simple Interface Class for POSIX Process.
Aim: Implement a simple interface class for a POSIX Process using multi-core
programming.
Prerequisites:
Basic Concepts on Multicore Programming and Data Structures and problem Solving
Concepts.
Objectives:
To learn concept of Simple Interface Class for POSIX Process.
Theory:
Portable Operating System Interface (POSIX) is a standard that defines a standard operating
system interface and environment, including a command interpreter (or ― shell ‖ ) and
common utility programs to support applications portability at the source code level. The
standard is intended be used by both applications developers and system implementors. To
make this book accessible to the broadest possible audience of system and application
developers we choose to present OS API material using the POSIX standard. The major
operating system environments — ZOS, Solaris, AIX, Windows, Mac OS X, Linux, HP -UX,
IRIX — all claim basic support for the POSIX standard. While each of these environments
has its own proprietary APIs, each also has support for the POSIX standard. Since the
concepts, examples, and programs we discuss are based on the POSIX standard, you can try
them out in virtually any environment. The POSIX standard plays the role of a cross -
platform pseudocode that allows us to cover the main concepts of multicore programming in a
language that can be implemented in all of the major environments. Further, POSIX
implements a kind of ― common denominator ‖ OS interface.
Interface
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface. An interface is not a class. Writing an
interface is similar to writing a class, but they are two different concepts. A class describes the
attributes and behaviors of an object. An interface contains behaviors that a class implements.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 82
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class. This simple interface class can be used to add a more object -
oriented approach to process management.
However, an interface is different from a class in several ways, including:
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Input:
Process Id, Path, Process State, Process Priority and process environment variable.
Output:
Output from header file method execution.
Conclusion:
Interface class is used to add a more object - oriented approach to process management.
Questions:
1. What is Interface Class?
2. What are uses of Simple Interface Class?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 83
Experiment No: 7
Title: POSIX semaphore
Aim: Implement POSIX semaphore using multi-core programming
Prerequisites:
Basic Concepts on Multicore Programming and Data Structures and problem Solving
Concepts.
Objectives:
To learn concept of Posix Semaphore.
Theory:
The POSIX semaphore defines a named binary semaphore. The name corresponds to a
pathname in the filesystem. Table below lists the basic functions for using a semaphore along
with a brief description.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 84
Input:
New Processes with attribute.
Output:
Path between multiple processes.
Conclusion:
Working of Posix semaphore is studied.
Questions:
1. What is posix semaphore?
2. What are uses of posix semaphore?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 85
GROUP C: ASSIGNMENTS
(Any one)
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 86
Experiment No: 1
Title: Matrix Multiplication.
Aim: Write a concurrent program for Matrix Multiplication. Effective use of
Multicore Architecture is expected.
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand the concept of multicore programming, shared memory,
concurrent model.
To analyze speedup achieved by the parallel algorithm when increases the size of the
input data and the number of cores of the architecture.
To understand the concept of multithreading.
Theory:
Given a matrix A(m × r) m rows and r columns, where each of its elements is denoted aij
with 1 ≤ i ≤ m and 1 ≤ j ≤ r, and a matrix B(r × n) of r rows and n columns, where each of its
elements is denoted bij with 1 ≤ i ≤ r, and 1 ≤ j ≤ n, the matrix C resulting from the operation
of multiplication of matrices A and B, C = A × B, is such that each of its elements is denoted
ij with 1 ≤ i ≤ m and 1 ≤ j
≤ n, and is calculated follows
The simplest way of multiplying two matrices takes about n3 steps.The number of operation
required to multiply A x B is:
m × n × (2r-1)
For simplicity, we will work with square matrices of size n x n. Considered the number of
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 87
processors available in parallel machines as p. The matrixes to multiply will be A and B.
Both will be treated as dense matrices (with few 0's), the result will be stored it in the matrix
C. It is assumed that the processing nodes are homogeneous, due this homogeneity it is
possible achieve load balancing.
Implementation
Consider two square matrices A and B of size n that have to be multiplied:
1. Partition these matrices in square blocks p, where p is the number of processes available.
2. Create a matrix of processes of size p1/2 x p1/2 so that each process can maintain a block
of A matrix and a block of B matrix.
3. Each block is sent to each process, and the copied sub blocks are multiplied together and
the results added to the partial results in the C sub-blocks.
4. The A sub-blocks are rolled one step to the left and the B sub-blocks are rolled one step
upward.
5. Repeat steps 3 y 4 sqrt(p) times.
Algorithm
Matrix-Multiply(A, B)
1 if columns [A] ≠ rows [B]
2 then error "incompatible dimensions"
3 else
4 for i =1 to rows [A]
5 for j = 1 to columns [B]
6 C[i, j] =0
7 for k = 1 to columns [A]
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 88
8 C[i, j]=C[i, j]+A[i, k]*B[k, j]
9 return C
To multiply two matrixes sufficient and necessary condition is "number of columns in
matrix A = number of rows in matrix B. Loop for each row in matrix A. Loop for each
columns in matrix B and initialize output matrix C to 0. This loop will run for each rows of
matrix A. Loop for each columns in matrix A. Multiply A[i,k] to B[k,j] and add this value to
C[i,j]. Return output matrix C.
Input:
Two Matrices
Output:
Product of two matrices.
Conclusion:
The distribution of data and computing division across multiple processors offers
many advantages: With Multicore architecture, it is required less effort in terms of
the timing required for data handling, since each process has its own portion.
Multicore architecture offers flexibility for data exchange.
Questions:
1. What is Multithreading?
2. Explain Multicore architecture?
3. What are advantages of using Multicore architecture?
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 89
Experiment No: 2
Title: Dining philosopher‟s problem using concurrent programming.
Aim: Write a concurrent program to implement the Dining philosopher‟s
problem. Effective use of Multicore Architecture is expected.
Prerequisites:
Data Structures and problem Solving
Objectives:
To understand the concept of multicore programming, shared memory,
semaphore, deadlock, concurrent model.
To understand the concept of multithreading.
Theory:
The dining philosopher’s problem is an example problem often used in concurrent
algorithm design to illustrate synchronization issues and techniques for resolving
them.
Illustration of the dining philosophers problem
Five silent philosophers sit at a table around a bowl of spaghetti. A fork is placed
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 90
between each pair of adjacent philosophers.
Each philosopher must alternately think and eat. However, a philosopher can only
eat spaghetti when he has both left and right forks. Each fork can be held by only
one philosopher and so a philosopher can use the fork only if it's not being used by
another philosopher. After he finishes eating, he needs to put down both forks so
they become available to others. A philosopher can grab the fork on his right or the
one on his left as they become available, but can't start eating before getting both of
them.
Eating is not limited by the amount of spaghetti left: assume an infinite supply.
The problem is how to design a discipline of behavior (a concurrent algorithm) such
that each philosopher won't starve; i.e., can forever continue to alternate between
eating and thinking assuming that any philosopher cannot know when others may
want to eat or think.
Issues
The problem was designed to illustrate the problem of avoiding deadlock, a system
state in which no progress is possible. To see that designing a proper solution to this
problem isn't obvious, consider the following proposal: instruct each philosopher to
behave as follows:
Think until the left fork is available; when it is, pick it up;
Think until the right fork is available; when it is, pick it up;
When both forks are held, eat for a fixed amount of time;
Then, put the right fork down;
Then, put the left fork down;
Repeat from the beginning.
This attempt at a solution fails: it allows the system to reach a deadlock state, in
which no progress is possible.
This is the state in which each philosopher has picked up the fork to the left, waiting
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 91
for the fork to the right to be put down. With the given instructions, this state can be
reached, and when it is reached, the philosophers will eternally wait for each other
to release a fork.
Resource starvation might also occur independently of deadlock if a particular
philosopher is unable to acquire both forks because of a timing problem. For
example there might be a rule that the philosophers put down a fork after waiting
ten minutes for the other fork to become available and wait a further ten minutes
before making their next attempt. This scheme eliminates the possibility of deadlock
(the system can always advance to a different state) but still suffers from the
problem of livelock. If all five philosophers appear in the dining room at exactly the
same time and each picks up the left fork at the same time the philosophers will
wait ten minutes until they all put their forks down and then wait a further ten
minutes before they all pick them up again.
Mutual exclusion is the core idea of the problem; the dining philosophers create a
generic and abstract scenario useful for explaining issues of this type. The failures
these philosophers may experience are analogous to the difficulties that arise in real
computer programming when multiple programs need exclusive access to shared
resources. These issues are studied in the branch of Concurrent Programming. The
original problems of Dijkstra were related to external devices like tape drives.
However, the difficulties studied in the Dining philosopher‟s problem arise far
more often when multiple processes access sets of data that are being updated.
Multithreading
A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread, and each thread defines a separate
path of execution. A multithreading is a specialized form of multitasking.
Multithreading requires less overhead than multitasking processing.
Creating a Thread:
Java defines two ways in which this can be accomplished:
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 92
You can implement the Runnable interface.
You can extend the Thread class itself.
Facilities:
Linux Operating Systems, GCC, Eclipse framework, VC++.
Algorithm:
The algorithm for the process is……….
4. Start.
5. Initialize the thread variables as required.
6. Create the threads representing philosophers.
7. Wait until the threads finishes execution.
8. Stop.
The algorithm for the philosopher is as……….
1. Start.
2. Wait for the left fork/spoon.
3. Wait for the right fork/spoon.
4. Start eating.
5. Release the left fork/spoon.
6. Release the right fork/spoon.
7. Stop
Input:
Numbers to be considered as philosophers and chopsticks.
Output:
Numbers.
Conclusion:
Hence, we have successfully implemented Dining philosopher‟s problem
multithreading.
Object Oriented and Multicore Programming SE (Comp)
Department of Computer Engineering ZES‟s DCOER, Pune-411041 Page 93
Questions:
1. What is Multithreading?
2. Explain concurrency model and sequential model?
3. Explain semaphore, semaphore, deadlock, concurrent model.
4. What is multicore programming, shared memory?
5. What are uses of multicore programming?
6. What are challenges of multicore programming?