0% found this document useful (0 votes)
15 views

OOPL Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

OOPL Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

lOMoARcPSD|28187839

OOPL Lab manual ds ds es ew

Database Management Systems (All India Shri Shivaji Memorial Society's College of
Engineering)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Jaya M ([email protected])
lOMoARcPSD|28187839

Course Code : 210247

Course Name: OOP and Computer Graphics Laboratory

Semester : I

PEO AND PO of the lab

Comp. Dept., SCOE 1 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Course Code : 210247

Course Name: OOP and Computer Graphics Laboratory

Semester : I

Course Name ↓ PEO‟s  I II III IV V

Object Oriented Programming Lab 2

Outcome-related learning
Outcome (a)

objectives
Outcome (b)

Outcome (d)

Outcome (g)

Outcome (h)

Outcome (k)
Outcome (c)

Outcome (e)

Outcome (f)

Outcome (i)

Outcome (j)
To explore the principles of
Object Oriented Programming 3
(OOP).

To understand object-oriented
concepts such as data
abstraction, encapsulation, 3 3
inheritance, dynamic binding,
and polymorphism.

To use the object-oriented


3 3 3
paradigm in program design.

To lay a foundation for advanced


2 3
programming.

Provide programming insight


3 3
using OOP constructs.

Summary 3 3 2 3 3

Comp. Dept., SCOE 2 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

University Syllabus

Operating System recommended: - 64-bit Open source Linux or its derivative


Programming tools recommended: - Open Source C++ Programming tool like G++/GCC,
OPENGL

Group A
1. Implement a class Complex which represents the Complex Number data type. Implement the
following operations:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >> to print and read Complex Numbers.

2. Develop an object oriented program in C++ to create a database of student


information system containing the following information: Name, Roll number, Class,
division, Date of Birth, Blood group, 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 constructor, destructor, static member
functions, friend class, this pointer, inline code and dynamic memory allocation operators-new
and delete as well as exception handling

3. Imagine a publishing company which does marketing for book and audio cassette versions.
Create a class publication that stores the title (a string) and price (type float) of publications.
From this class derive two classes: book which adds a page count (type int) and tape which adds
a playing time in minutes (type float).
Write a program that instantiates the book and tape class, 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

4. Write a C++ program that creates an output file, writes information to it, closes the file and
open it again as an input file and read the information from the file.

5. Write a function template selection Sort. Write a program that inputs, sorts and outputs an
integer array and a float array.

Comp. Dept., SCOE 3 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Group C

6. Write C++ program using STL for Sorting and searching with user-defined records such as
Person Record (Name, birth date, telephone no), item record (item code, item name, quantity and
cost)

7. Write a program in C++ to use map associative container. The keys will be the names of states
and the values will be the populations of the states. When the program runs, the user is prompted
to type the name of a state. The program then looks in the map, using the state name as an index
and returns the population of the state.

Comp. Dept., SCOE 4 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

List of Assignments
Sr. No. TITLE

G Group A

1 Implement a class Complex which represents the Complex Number data type.
Implement the following operations:
1. Constructor (including a default constructor which creates the complex
number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >> to print and read Complex Numbers.
2. Develop an object oriented program in C++ to create a database of student
information system containing the following information: Name, Roll number,
Class, division, Date of Birth, Blood group, 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
constructor, destructor, static member functions, friend class, this pointer, inline
code and dynamic memory allocation operators-new and delete as well as exception
handling
3. Imagine a publishing company which does marketing for book and audio cassette
versions. Create a class publication that stores the title (a string) and price (type
float) of publications. From this class derive two classes: book which adds a page
count (type int) and tape which adds a playing time in minutes (type float).
Write a program that instantiates the book and tape class, 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

4. Write a C++ program that creates an output file, writes information to it, closes the
file and open it again as an input file and read the information from the file.
5. Write a function template selection Sort. Write a program that inputs, sorts and
outputs an int array and a float array.
5.
Group C

6. Write C++ program using STL for Sorting and searching with user-defined records
such as Person Record (Name, birth date, telephone no), item record (item code,
item name, quantity and cost) using vector container.

Comp. Dept., SCOE 5 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

7. Write a program in C++ to use map associative container. The keys will be the
names of states and the values will be the populations of the states. When the
program runs, the user is prompted to type the name of a state. The program then
looks in the map, using the state name as an index and returns the population of the
state.

Comp. Dept., SCOE 6 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 01

Title: Implement a class Complex which represents the Complex Number data type. Implement
the following operations:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator + to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >> to print and read Complex Numbers.

Objectives:
 To learn the concept of operator overloading in depth.

Theory:
Operator Overloading:
To define an additional task to an operator, we must specify what it means in relation to the class
to which the operator is applied. This is done with the help of a special function called operator
function which describes the task. The general form of the operator function is :
Return type classname::operator op(arglist)
{
Function body (Assigned Task)
}
Where Return type is the type of the value returned by the specified operation and op is the
operator being overloaded. The op is preceded by the keyword operator. Operator op is the
function name.

Operator functions must be either member functions (non-static) or friend functions.

Advantage of Operator Overloading:


Operator overloading provides a flexible options for creations of new definition for most of the
C++ operators.

Comp. Dept., SCOE 7 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Rules for overloading operators:


1. Only existing operators can be overloaded. New operators cannot be created.
2. The overloaded operator must have at least one operand that is user-defined type.
3. We cannot change the basic meaning of an operator. That is to say, we cannot redefine
the plus (+) operator to subtract one value from the other.
4. Overloaded operators follow the syntax rules of the original operators. They cannot be
overridden.
5. There are some operators that cannot be overloaded.
6. We cannot use friend functions to overload certain operators. However, member function
can be used to overload them.
7. Unary operators, overloaded by means of a member function, take no explicit arguments
and return no explicit values, but, those overloaded by means of a friend function, take
one reference argument (the object of the relevant class).
8. Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
9. When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
10. Binary arithmetic operators such as +,-,*,/ must explicitly return a value. They must not
attempt to change their own arguments.

Operators that cannot be overloaded:

Sizeof Size of operator


. Membership operator
.* Pointer-to-member operator
:: Scope Resolution operator
?: Conditional operator

Operators that cannot be overloaded using friend function:

= Assignment operator

Comp. Dept., SCOE 8 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

() Function call operator


[] Subscripting operator
-> Class member access operator

Algorithm:
Steps:
1. Accept the input for two complex numbers using overloaded Insertion operator.
2. Accept the choice of operation to be performed from the user.
3. Perform operations like Addition, Multiplication etc. based on user‟s choice.

Flowchart : << Students should prepare a flowchart >>


Test Cases:

Feature to test Input Expected output Observed output


Overloaded Values for the real The complex number The complex number
Extraction operator and imaginary parts is constructed with is constructed with
for accepting the of the complex entered values. entered values.
input for complex number.
numbers.
Overloaded Insertion Complex number Real and imaginary Real and imaginary
operator for printing object whose parts parts of the complex parts of the complex
complex numbers. should be printed. number are printed. number are printed.
Overloaded „+‟ Two complex Resultant complex Resultant complex
operator for an numbers. number is returned and number is returned and
addition of two then printed. then printed.
complex numbers.
Overloaded „*‟ Two complex Resultant/Product Resultant/Product
operator for numbers. complex number is complex number is
multiplication of two returned and then returned and then
complex numbers. printed. printed.

Comp. Dept., SCOE 9 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Conclusion:
Hence, we have successfully studied the concept of operator overloading.

FAQ
1. What are different operators? (You can mention types also like Unary and Binary operators)
2. What is an operator overloading? What is the need of operator overloading? How it works?
(Hint: Left hand operand‟s operator function is called. Give 2-3 lines explaining how operand‟s
operator function is called for both unary and binary operator)
3. How to overload operators? (Hint: by writing operator function).
4. What do you mean by compile time polymorphism?
5. When operator overloading takes place whether at run time or compile time? i.e. Is operator
overloading compile time (static polymorphism)?
6. How unary and binary operators can be overloaded using friend function?
8. Which operators cannot be overloaded?
9. Which operators can be overloaded only using friend function?
10. What is reference variable? Why arguments are passed as reference variable in case of “<<”
and “>>” operator overloading ?

Comp. Dept., SCOE 10 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 02

Title: Develop an object oriented program in C++ to create a database of student


information system containing the following information: Name, Roll number, Class,
division, Date of Birth, Blood group, 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 constructor, destructor, static member
functions, friend class, this pointer, inline code and dynamic memory allocation operators-new
and delete as well as exception handling

Objectives:
 To learn the concept of constructor, default constructor, Copy constructor, destructor
 To learn the concept of static member functions, friend class, this pointer, inline code
 To learn the concept of dynamic memory allocation and deallocation (use of new and
delete operator).
 To learn the concept of Exception Handling

Theory:
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. The copy constructor is used to −
 Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.
If the class has pointer variables and has some dynamic memory allocations, then it is a
must to have a copy constructor.
Syntax:
classname (const classname &obj)
{
// body of constructor
}
Here, obj is a reference to an object that is being used to initialize another object.

Destructors
Destructor is a member function which destructs or deletes an object.

When is destructor called?


A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends

Comp. Dept., SCOE 11 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

(3) a block containing local variables ends


(4) a delete operator is called

How destructors are different from a normal member function?


Destructors have same name as the class preceded by a tilde (~)
Destructors don‟t take any argument and don‟t return anything
Example:
# include<iostream>
using namespace std;

class Point
{
int x,y;
public:
//Parameterized constructor
Point(int x1, int y1)
{
x=x1;
y=y1;
cout<<"Constructor is called"<<endl;
}

//Copy Constructor
Point(const Point &p2)
{
x=p2.x;
y=p2.y;
}

int getx()
{
return x;
}
int gety()
{
return y;
}

~Point()
{
cout<<"Destructor is called"<<endl;

Comp. Dept., SCOE 12 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

}
};

int main()
{
Point p1(10,12);
Point p2=p1; //called copy constructor

cout<<"p1.x="<<p1.getx()<<", p1.y="<<p1.gety()<<endl;
cout<<"p2.x="<<p2.getx()<<", p2.y="<<p2.gety()<<endl;

return 0;
}
Static Members of a C++ Class
 Define class members static using static keyword.
 When we declare a member of a class as static it means no matter how many objects of
the class are created, there is only one copy of the static member.
 A static member is shared by all objects of the class.
 All static data is initialized to zero when the first object is created, if no other
initialization is present.
 We can't put it in the class definition but it can be initialized outside the class as done in
the following example by redeclaring the static variable, using the scope resolution
operator :: to identify which class it belongs to.
 E.g. datatype classname : : variable name=0;

Static Function Members:

 By declaring a function member as static, you make it independent of any particular


object of the class.
 A static member function can be called even if no objects of the class exist
 The static functions are accessed using only the class name and the scope resolution
operator ::
 A static member function can only access static data member, other static member
functions and any other functions from outside the class.
 Static member functions have a class scope and they do not have access to
the this pointer of the class.
 You could use a static member function to determine whether some objects of the class
have been created or not.

Comp. Dept., SCOE 13 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

this Pointer
 Every object in C++ has access to its own address through an important pointer
called this pointer (->).
 The this pointer is an implicit parameter to all member functions. Therefore, inside a
member function, this may be used to refer to the invoking object.

 Friend functions do not have a this pointer, because friends are not members of a class.
Only member functions have a this pointer.
Friend class and Friend function in C++
 A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class.
 Even though the prototypes for friend functions appear in the class definition, friends are
not member functions.
 A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition
with keyword friend
Inline Function
 C++ inline function is powerful concept that is commonly used with classes.
 If a function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
 Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again otherwise it
will continue with old functionality.
 To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function.
 The compiler can ignore the inline qualifier in case defined function is more than a line.
C++ provides two dynamic allocation operators: new and delete.

These operators are used to allocate and free memory at run time. Dynamic allocation is an
important part of almost all real-world programs. C++ also supports dynamic memory allocation
functions, called malloc( ) and free( ). These are included for the sake of compatibility with C.
However, for C++ code, you should use the new and delete operators because they have several
advantages. The new operator allocates memory and returns a pointer to the start of it. The delete

Comp. Dept., SCOE 14 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

operator frees memory previously allocated using new. The general forms of new and delete are
shown here:

p_var = new type;

delete p_var;

Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an
item of type type. Since the heap is finite, it can become exhausted. If there is insufficient
available memory to fill an allocation request, then new will fail and a bad_alloc exception will
be generated. This exception is defined in the header <new>. Your program should handle this
exception and take appropriate action if a failure occurs. If this exception is not handled by your
program, then your program will be terminated. The actions of new on failure as just described
are specified by Standard C++. The trouble is that not all compilers, especially older ones, will
have implemented new in compliance with Standard C++. Here is a program that allocates
memory to hold an integer:

#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p;
p = new int; // allocate space for an int
*p = 100;
cout << "At " << p << " "; cout << "is the value " << *p << "\n";
delete p;
return 0;
}
This program assigns to p an address in the heap that is large enough to hold an integer. It then
assigns that memory the value 100 and displays the contents of the memory on the screen.

Comp. Dept., SCOE 15 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Finally, it frees the dynamically allocated memory. Remember, if your compiler implements new
such that it returns null on failure, you must change the preceding program appropriately. The
delete operator must be used only with a valid pointer previously allocated by using new. Using
any other type of pointer with delete is undefined and will almost certainly cause serious
problems, such as a system crash. Although new and delete perform functions similar to malloc(
) and free( ), they have several advantages. First, new automatically allocates enough memory to
hold an object of the specified type. You do not need to use the sizeof operator. Because the size
is computed automatically, it eliminates any possibility for error in this regard. Second, new
automatically returns a pointer of the specified type. You don't need to use an explicit type cast
as you do when allocating memory by using malloc( ). Finally, both new and delete can be
overloaded, allowing you to create customized allocation systems. Although there is no formal
rule that states this, it is best not to mix new and delete with malloc( ) and free( ) in the same
program. There is no guarantee that they are mutually compatible. Initializing Allocated Memory
You can initialize allocated memory to some known value by putting an initializer after the type
name in the new statement.

Here is the general form of new when an initialization is included:

p_var = new var_type (initializer);

Of course, the type of the initializer must be compatible with the type of data for which memory
is being allocated. This program gives the allocated integer an initial value of 87:

#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p;
p = new int (87); // initialize to 87
cout << "At " << p << " "; cout << "is the value " << *p << "\n";
delete p;

Comp. Dept., SCOE 16 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

return 0;
}

Allocating Arrays You can allocate arrays using new by using this general form:

p_var = new array_type [size];

Here, size specifies the number of elements in the array. To free an array, use this form of delete:

delete [ ] p_var;

Here, the [ ] informs delete that an array is being released. For example, the next program
allocates a 10-element integer array.

#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p, i;
p = new int [10]; // allocate 10 integer array
}
for(i=0; i<10; i++ ) p[i] = i;
for(i=0; i<10; i++) cout << p[i] << " ";
delete [] p; // release the array
return 0;
}
Notice the delete statement. As just mentioned, when an array allocated by new is released,
delete must be made aware that an array is being freed by using the [ ]. (As you will see in the
next section, this is especially important when you are allocating arrays of objects.) One
restriction applies to allocating arrays: They may not be given initial values. That is, you may not
specify an initializer when allocating arrays.

Comp. Dept., SCOE 17 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Allocating Objects You can allocate objects dynamically by using new:

When you do this, an object is created and a pointer is returned to it. The dynamically created
object acts just like any other object. When it is created, its constructor (if it has one) is called.
When the object is freed, its destructor is executed.

Exception Handling
 An exception is a problem that arises during the execution of a program.
 A C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.
 Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
o throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
o catch − A program catches an exception with an exception handler at the place in
a program where you want to handle the problem. The catch keyword indicates
the catching of an exception.
o try − A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
Syntax:
try
{
// protected code
}
catch( ExceptionName e1 ) {
// catch block
}
catch( ExceptionName e2 ) {
// catch block
}
catch( ExceptionName eN ) {
// catch block
}

Throw Exception/Statement:
double division(int a, int b)
{
if( b == 0 )
{

Comp. Dept., SCOE 18 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

throw "Division by zero condition!";


}
return (a/b);
}
Catch Exception
try
{
// protected code
}
catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Algorithm:

1. Start
2. Accept Student information from user.
3. Display information using all mentioned concepts
4. Stop

Flowchart : << Students should prepare a flowchart >>

Conclusion:
Hence, we have studied and implemented type of constructors, destructor, static member
function, friend class, this pointer, inline code and dynamic memory allocation operators new
and delete successfully.

FAQ

1. What is Object Oriented Programming?


2. What is class? What is an object?
3. Explain difference between member function (i.e. class methods) and non -
member function.
4. What is this pointer? Explain with small example.
5. What is inline function?
Comp. Dept., SCOE 19 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

6. What is friend function? What is the advantage of friend function?


7. What are new and delete? (Hint: These are operators used for dynamic memory
allocation and de allocation).
8. Why is the need of dynamic memory allocation?
9. What do you mean by static data members and static member function? What is
the need of both?
10. How memory is allocated for static members and non-static members?
11. Can static function access non-static data?
12. What is the purpose/use of constructor and destructor?
13. What are different types of constructor (Hint: Default, with arguments,
overloaded constructor and copy constructor).

Comp. Dept., SCOE 20 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 03

Title: Imagine a publishing company which does marketing for book and audio cassette
versions. Create a class publication that stores the title (a string) and price (type float) of
publications. From this class derive two classes: book which adds a page count (type int) and
tape which adds a playing time in minutes (type float).
Write a program that instantiates the book and tape class, allows user to enter data and displays
the data members. If an exception is caught, replace all the data member values with zero
values.
Objective:
 To understand the concepts of inheritance and apply hierarchical inheritance
 To learn the concept of exception handling.
Theory:
Inheritance is probably the most powerful feature of object-oriented programming, after classes
themselves. Inheritance is the process of creating new classes, called derived classes, from
existing or base classes. The derived class inherits all the capabilities of the base class but can
add embellishments and refinements of its own. The base class is unchanged by this process. The
inheritance relationship is shown in Figure 10. 10.1

Figure 10. 1: Inheritance

The arrow in Figure 10. 1 goes in the opposite direction of what you might expect. If it pointed
down we would label it inheritance. However, the more common approach is to point the arrow
up, from the derived class to the base class, and to think of it as a “derived from” arrow.
Inheritance is an essential part of OOP. Its big payoff is that it permits code usability. Once a
base class is written and debugged, it need not be touched again, but, using inheritance, can
nevertheless be adapted to work in different situations. Reusing existing code saves time and

Comp. Dept., SCOE 21 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

money and increases a program‟s reliability. Inheritance can also help in the original
conceptualization of a programming problem, and in the overall design of the program.

An important result of reusability is the ease of distributing class libraries. A programmer can
use a class created by another person or company, and, without modifying it, derive other classes
from it that are suited to particular situations. Multiple classes derived from same base class
called as Hierarchical Inheritance. A class can be derived from more than one base class. This is
called multiple inheritance.

Hierarchical inheritance is defined as the process of deriving more than one class from a base
class. Syntax is as follows:

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Figure 10.2 shows how this looks when a class C is derived from base classes A and B.

Figure 10.2: Multiple Inheritance

Comp. Dept., SCOE 22 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

The syntax for multiple inheritance is similar to that for single inheritance. In the situation
shown in Figure 10.2, the relationship is expressed like this:
class A // base class A
{
};
class B // base class B
{
};
class C : public A, public B // C is derived from A and B
{
};
The base classes from which C is derived are listed following the colon in C‟s specification;
they are separated by commas.

The colon indicates that the derived class name is derived from the base class name. The
visibility mode is optional and if present, may be either private or public. The default visibility
mode is private. Visibility mode specifies whether the features of the base class are privately
derived or publicly derived.

When a base class is privately inherited by derived class, „public members‟ of the base class
become „private members‟ of the derived class and therefore the public members of base class
can only be accessed by the member functions of the derived class. They are in inaccessible to
the objects of the derived class. The public member of the class can be accessed by its own
objects using the dot operator. So, the result is no member of the base class is accessible to the
objects of derived class.

On the other hand, when the base class is publicly inherited, „public members‟ of the base class
become „public members‟ of the derived class and therefore they are accessible to the objects of
the derived class. In above both cases, the private members are not inherited and therefore, the
private members of the base class will never become members of the derived class.
For this reason, C++ provides a third visibility modifier i.e. Protected , it serves a limited
purpose in inheritance. A member declared as protected is accessible by the member functions
within its class and any class derived from it. It cannot be accessed by the functions outside these
two classes.
Below figure shows inheritance and accessibility of data according to the access specifiers used.

Comp. Dept., SCOE 23 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Figure 10. 3: Inheritance and accessibility

Exception Handling
 Exceptions are errors that occur at runtime.
 Examples - conditions such as division by zero, access to an array outside of its bounds,
or running out of memory or disk space.
 When an exceptional condition is encountered, it is important to identify and deal with
effectively.
 C++ provides built-in language features to detect and handle exceptions which are
basically run time errors.
 Exception is of two kinds- synchronous exception and asynchronous exception.
o Errors such as “out-of-range index” and “overflow” belong to synchronous type
exceptions.
o The errors that are caused by events beyond the control of the program (such as
keyboard interrupts) are called asynchronous exception.
 Proposed exception handling mechanism in C++ is designed to handle only synchronous
exceptions.
 Steps for exception handling

 It is basically built of three key words- try, throw and catch


 Syntax

Comp. Dept., SCOE 24 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Multiple Catch Statement

Comp. Dept., SCOE 25 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Algorithm:

1. Start
2. Declare variable and member functions of the base class publication
3. Inherit the data members of base classes into a derived class i.e. book and tape
4. In main() create the object of the derived class and call the member functions of
all base classes by calling their member functions using derived class object.
5. Run the program providing input values.
6. See the output
7. End

Conclusion: - Thus we have studied and implemented the concept of Inheritance.

FAQ:

1. What is Inheritance? What is the advantage of Inheritance? (Hint: Reusability)


2. What are the different types of Inheritance? (Write in very brief with small example).
3. What is the order of execution of constructor and destructor in case of inheritance?
4. How do we pass arguments to the base class constructor from derived class constructor?
5. How do we access base class‟s data member and member function in derived class if they
have same name as that of derived class.
6. Explain all types of access specifiers. (Private, Public and Protected).
7. What is exception?
8. What is synchronous exception and asynchronous exception?
9. Can we handle asynchronous exception using C++ exception handling mechanism?
10. What are the four steps of exception handling?
11. What are the different key words used in exception handling?
12. What is multiple catch?

Comp. Dept., SCOE 26 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 04

Title: Write a C++ program that creates an output file, writes information to it, closes the file
and open it again as an input file and read the information from the file.

Objectives:
 To learn the concept of File Handling.

Theory:
Stream Class:
A stream is a general name given to a flow of data. In C++ a stream is represented by an object
of a particular class. Different streams are used to represent different kinds of data flow. For
example, the ifstream class represents data flow from input disk files.

Advantages of Stream Class:


One reason is simplicity. There are no formatting characters (like %d, %f etc.) in streams, since
each object already knows how to display itself. This removes a major source of errors.

Another reason is that you can overload existing operators and functions, such as the insertion
(<<) and extraction (>>) operators, to work with classes that you create. This makes your own
classes work in the same way as the built-in types, which again makes programming easier and
more error free.

The Stream Class Hierarchy


The stream classes are arranged in a rather complex hierarchy as shown in the figure below.

Comp. Dept., SCOE 27 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Disk file I/O with streams


Most programs need to save data to disk files and read it back in. Working with disk files
requires another set of classes: ifstream for input, fstream for both input and output, and ofstream
for output. Objects of these classes can be associated with disk files, and we can use their
member functions to read and write to the files.

Formatted File I/O


In formatted I/O, numbers are stored on disk as a series of characters. Thus 6.02, rather than

Comp. Dept., SCOE 28 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

being stored as a 4-byte type float or an 8-byte type double, is stored as the characters „6‟, „.‟,
„0‟, and „2‟. This can be inefficient for numbers with many digits, but it‟s appropriate in many
situations and easy to implement.
Opening a file :
For opening file in output mode i.e. for writing purpose we create an object of ofstream class. At
the same time, we initialize it to the file (e.g. DATA.TXT). This initialization sets aside various
resources for the file, and accesses or opens the file of that name on the disk. If the file doesn‟t
exist, it is created. If it does exist, it is truncated and the new data replaces the old.

We can open the file using open() function as follows.


fstream file;
file.open(“GROUP.DAT”, ios::app | ios::out);

We create the file in one statement and open it in another, using the open() function, which is a
member of the fstream class. This is a useful approach in situations where the open may fail.
You can create a stream object once, and then try repeatedly to open it, without the overhead of
creating a new stream object each time.

Read and Write operations on file:


The ofstream object acts much as cout , so we can use the insertion operator (<<) to output
variables of any basic type to the file. This works because the insertion operator is appropriately
overloaded in ostream, from which ofstream is derived. When ofstream object goes out of scope
its destructor is called, which closes the file, so we don‟t need to close the file explicitly.

For reading the data we can use extraction operator (>>).

For detecting end-of-file we can use end-of-file (EOF) condition. The EOF is a signal sent to the
program from the operating system when there is no more data to read.

e.g. while( ! infile.eof() ) // until eof encountered

Comp. Dept., SCOE 29 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

However, checking specifically for an eofbit means that we won‟t detect the other error flags,
such as the failbit and badbit, which may also occur, although more rarely. To do this, we can
change loop condition:

while( infile.good() ) // until any error encountered

You can also test the stream directly. Any stream object, such as infile, has a value that can be
tested for the usual error conditions, including EOF. If any such condition is true, the object
returns a zero value. If everything is going well, the object returns a nonzero value. This value is
actually a pointer, but the “address” returned has no significance except to be tested for a zero or
nonzero value.
e.g while( infile ) // until any error encountered

You can use close() function to close the file.


e.g. os.close(); where os is an object of ofstream class.

When you open the same file for reading and writing purpose in the same program then you have
to use close function after either of reading or writing operations.

Algorithm:
Steps:
 Open an output file.
 Accept input data from the user and then write in to the file.
 Close the file.
 Open the file in input mode for reading purpose, read the data and display it.

Flowchart : << Students should prepare a flowchart >>

Comp. Dept., SCOE 30 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Test Cases:

Feature to test Input Expected output Observed output


Open the file with Filename File is opened in File is opened in
ofstream type object. output mode. If file output mode. If file
exists then its contents exists then its contents
are truncated are truncated
otherwise new file otherwise new file
will be created with will be created with
the specified name. the specified name.
Open the already Filename File is opened in File is opened in
existing file. output mode. If file output mode. If file
exists then its contents exists then its contents
are truncated. are truncated.
Open the file with Filename File is opened for in File is opened for in
ifstream type object. for reading purpose. for reading purpose.

Conclusion:
Hence, we have successfully studied the concept of file handling.

FAQ
1. What is need of file handling?
2. What are stream errors?
3. What are formatted I/O and unformatted I/O?
4. What is Stream? What are advantages of Stream class?
5. What are istream and ostream classes? Write in brief about the methods supported by
them.
6. Write methods (Functions) of istream and ostream class in tabular format.
7. Explain in brief function used for character I/O. (Don‟t give example)
8. How formatted I/O is performed? (Hint: using extraction and insertion operators, Don‟t
give example)

Comp. Dept., SCOE 31 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 05

Title: Write a function template selection Sort. Write a program that inputs, sorts and outputs an
int array and a float array.
Objectives:
 To learn the concept of templates.
 To learn the concept of pure generic functions.

Theory:
Templates
 Generic programming is an approach where generic types are used as parameters in
algorithms so that they work for a variety of suitable data types and data structures.
 A generic function defines a general set of operations that will be applied to various types
of data.
 The type of data that the function will operate upon is passed to it as a parameter.
 Through a generic function, a single general procedure can be applied to a wide range of
data.
 As you probably know, many algorithms are logically the same no matter what type of
data is being operated upon.
 By creating a generic function, you can define the nature of the algorithm, independent of
any data.
 Once you have done this, the compiler will automatically generate the correct code for
the type of data that is actually
used when you execute the function.
 In essence, when you create a generic function you
are creating a function that can automatically overload itself.
 A generic function is created using the keyword template.
 Templates can be used to create family of classes or functions.
 function template can be used to create a family of function with different argument
types.
 General format of a function template is:

Comp. Dept., SCOE 32 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Test Cases

Feature to test Input Expected output Observed output


Sorting of integer Random integer sorted integer
numbers stored in an numbers stored in
array same array
Sorting of float Random float sorted float numbers
numbers stored in an stored in same array
array
The test cases can be designed for character data, long data.

Conclusion:
Hence, we have successfully studied and implemented function template concept

FAQ’s:
1. What is function template?
2. What is class template?
3. What is the application of templates?
4. What is generic programming?
5. How the instantiation of function template happens?

Comp. Dept., SCOE 33 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 06

Title: Write C++ program using STL for sorting and searching with user defined records such
as person record(Name, DOB, Telephone number), Item record (Item code, name, cost, quantity)
using vector container.

Objectives:
 To learn the concept of Standard Template Library in depth using vector container.

Theory:
 Vector provide an alternative to the built in array
 A Vector is self-grown.
 A vector changes size dynamically.
 Use it instead of built in array.
 Vector can be assigned to one another. This is not possible with pointer based C-like
array.
 Vector elements occupy contiguous cells in memory just as C or C++.
 An important part of every container is the type of iterator it supports . This determine
which algorithms can be applied to the container. A Vector supports random access
iterators.
 Class template vector is most commonly used when the data in the container must be
easily accessible via a subscript or will be sorted.
 When vector‟s memory is exhausted, the vector allocates a large contiguous area of
memory, copies the original elements into the new memory and deallocates the old
memory.
 All iterator operations can be applied to a vector iterator.
 All STL algorithms can operate on a vector.
Defining a vector
Syntax: vector<of what>
For example
Vector<int>- vector of integers
Vector<string>- vector of strings.
Comp. Dept., SCOE 34 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

Vector<int *>- vector of pointers to integers


Vector <Shape> vector of shape objects.

Conclusion: Hence, we have studied the concept of vector in depth and implemented the
program for searching and sorting with user defined records.

FAQ
1. What is algorithm component of STL?
2. Explain at least 5 algorithms in STL? (Find,Count, Search, Sort, Merge: Write 1-2 line
descriptions of these)
3. What are the advantages of using STL? (Very important)
4. What is Vector?

Comp. Dept., SCOE 35 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

ASSIGNMENT NO: 07

Title: Write a program in C++ to use map associative container. The keys will be the names of
states and the values will be the populations of the states. When the program runs, the user is
prompted to type the name of a state. The program then looks in the map, using the state name as
an index and returns the population of the state.

Objectives:
 To learn the concept of Standard Template Library in depth using vector container.

Theory:

MAP Container in STL


Maps are used to replicate associative arrays. Maps contain sorted key-value pair, in which each
key is unique and cannot be changed, and it can be inserted or deleted but cannot be altered.
Value associated with keys can be altered. We can search, remove and insert in a map
within O(n) time complexity.
For example: A map of students where roll number is the key and name is the value can be
represented graphically as :

Notice that keys are arranged in ascending order, its because maps always arrange its keys in
sorted order. In case the keys are of string type, they are sorted lexicographically.

Creating a Map in C++ STL


Maps can easily be created using the following statement:

Comp. Dept., SCOE 36 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

map<key_type , value_type> map_name;


This will create a map with key of type Key_type and value of type value_type. One thing
which is to remembered is that key of a map and corresponding values are always inserted as a
pair, you cannot insert only key or just a value in a map.

Member Functions of Map in C++ STL


Following are some of the commonly used function of Map container in STL:

1. at and [ ]
Both at and [ ] are used for accessing the elements in the map. The only difference between them
is that at throws an exception if the accessed key is not present in the map, on the other hand
operator [ ] inserts the key in the map if the key is not present already in the map.

2. empty, size and max_size


empty() returns boolean true if the map is empty, else it returns Boolean false. size() returns
number of entries in the map, an entry consist of a key and a value. max_size() returns the upper
bound of the entries that a map can contain (maximum possible entries) based on the memory
allocated to the map.

3. insert and insert_or_assign

insert() is used to insert entries in the map. Since keys are unique in a map, it first checks that
whether the given key is already present in the map or not, if it is present the entry is not inserted
in the map and the iterator to the existing key is returned otherwise new entry is inserted in the
map.
There are two variations of insert():

 insert(pair) : In this variation, a pair of key and value is inserted in the map. The inserted
pair is always inserted at the appropriate position as keys are arranged in sorted order.
 insert(start_itr , end_itr): This variation inserts the entries in range defined
by start_itr and end_itr of another map.

4. erase and clear


erase() removes the entry from the map pointed by the iterator (which is passed as parameter),
however if we want to remove all the elements from the map, we can use clear(), it clears the
map and sets its size to 0.
There are two variations of erase:

Comp. Dept., SCOE 37 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])


lOMoARcPSD|28187839

 erase(iterator_itr) : This removes entry from the map pointed by iterator iterator_itr,
reducing the size of map by 1.
 erase(start_iterator, end_iterator) : It removes the elements in range specified by
the start_iterator and end_iterator.

5. begin, end and find


begin, end and find returns an iterator. begin() returns the iterator to the starting entry of the
map, end() returns the iterator next to the last entry in the map and find() returns the iterator to
the entry having key equal to given key (passed as parameter).

Conclusion: Hence, we have studied and implemented the concept of map associative container
in depth successfully.

FAQ
1. What are Maps in C++
2. Explain member functions of map

Comp. Dept., SCOE 38 Object Oriented Programming Lab

Downloaded by Jaya M ([email protected])

You might also like