NEW - OOPS - Using C++Lab Manual - 3rd - NamitaGoyal
NEW - OOPS - Using C++Lab Manual - 3rd - NamitaGoyal
OF
OBJECT ORIENTED
PROGRAMMING USING C++
(CIC-257)
To attain global excellence through education, innovation, research, and work ethics with the
commitment to serve humanity.
M1. To excel in the field by imparting quality education and skills for software devel-
opment and applications.
M2. To establish a conducive environment that promotes intellectual growth and re-
search.
M3. To facilitate students to acquire entrepreneurial skills for innovation and product
development.
M4. To encourage students to participate in competitive events and industry interaction
with a focus on continuous learning.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
PEO1 The graduates would utilize their professional skills in Information Technology to
address real-world and societal challenges.
PEO2 The graduates would become successful entrepreneurs and motivators.
PEO3 The graduates would pursue research globally and engage in producing novel prod-
ucts to serve humanity.
PEO4 The graduates would exhibit collaborative abilities with adherence to professional
ethics.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
PSO1 Students are equipped with programming technologies applied in the indus-
try.
PSO2 Students are able to provide efficient solutions for emerging challenges in
the computation domain such as Artificial Intelligence, Data Science, Web
Technologies.
PSO3 Students are able to apply domain knowledge and expertise in the field of
Information Technology for enhancing research capability to transform in-
novative ideas into reality.
CO OF THE LAB SUBJECT AND ITS MAPPING
WITH PO AND PSO
TABLE OF CONTENTS
The Object-Oriented Programming using C++ course is designed to provide students with a
solid foundation in object-oriented programming principles and the C++ programming lan-
guage. Throughout the course, students will learn how to design, implement, and manipulate
objects to solve complex problems. The course will cover key concepts such as classes, objects,
inheritance, polymorphism, encapsulation, and abstraction. Following is a comprehensive plan
for your Object-Oriented Programming using C++ course which describes how each compo-
nent contributes to the overall learning experience:
1. Lab Setup: The lab should provide a computer environment equipped with the necessary
software tools and compilers for C++ programming. This includes an integrated development
environment (IDE) or a text editor, a C++ compiler, and debugging tools.
2. Programming Exercises: The lab sessions typically involve a series of programming exer-
cises that cover various aspects of C++ programming. These exercises may focus on topics like
basic syntax, control structures, functions, arrays, classes, inheritance, polymorphism, data
structures, algorithms, file handling, and more.
3. Hands-on Coding: In the lab, students are encouraged to actively write code to solve pro-
gramming problems and complete the given exercises. They can experiment with different pro-
gramming techniques, implement algorithms, and practice coding best practices.
4. Debugging and Error Handling: Debugging is an essential part of programming, and the lab
provides an environment for students to practice debugging techniques. Students learn to iden-
tify and fix errors in their programs, use debugging tools to trace program execution, and handle
exceptions that may occur during program execution.
5. Experiments beyond syllabus/Practice programmes: Lab courses often include few experi-
ments that are not in GGSIPU list and practice program related to concepts given in syllabus,
requires students to work on more extensive programming tasks. This practice may involve
developing software applications, implementing algorithms, solving coding problems, or work-
ing on group projects to encourage teamwork and collaboration.
6. Code Review and Feedback: Lab instructors or teaching assistants provide guidance, review
students' code, and offer feedback on their programming solutions. This helps students improve
their coding style, understand best practices, and learn from their mistakes.
HARDWARE & SOFTWARE REQUIREMENT
The students are required to maintain the lab records as per the in-
struction:
1. All the record files should have a cover page as per the for-
mat.
2. All the record files should have an index as per the format.
3. All the record should have the following:
I. Date
II. Aim
III. Algorithm or The Procedure to be followed
IV. Program
V. Output
VI. Viva Questions
MARKING SCHEME
FOR THE
PRACTICAL EXAMINATION
Faculty Name:
(16”, Times New Roman) Student Name:
Roll No.:
Semester:
Batch:
(16”, Times New Roman)
1.
2.
3.
4.
5.
b) Experiments beyond the list provided by GGSIPU
R1 R2 R3 R4 R5
1.
2.
3.
4.
5.
EXPERIMENT – 1
AIM:
Write a program for multiplication of two matrices using OOP.
THEORY:
Matrix is a rectangular array of m × n numbers (real or complex) in the form of m horizontal
lines (called rows) and n vertical lines (called columns) is called a matrix of order m by n,
written as m × n matrix.
Create a matrix class that represents a matrix with basic operations such as setting values,
getting values, displaying the matrix and matrix multiply function performs matrix multipli-
cation. In addition to simple illustration, in a real-world scenario, you can to add more error
handling, optimize the matrix multiplication algorithm, and perhaps implement additional
matrix operations.
ALGORITHM:
Step 1: If the original matrices are of size n1 x n2 and m1 x m2, create a resultant matrix of
size n1 x m2.
Step 2: Three nested loops will be used for the multiplication of the matrices.
Step 3: The first two loops are used to iterate over the rows and columns of the result ma-
trix, respectively.
Step 4: The innermost loop performs the multiplication of corresponding elements from the
current row of the first matrix and the current column of the second matrix.
Step 5: Add these products to get the element of the result matrix.
Step 6: Repeat these steps for all elements of the result matrix.
Step 7: Stop the program.
VIVA QUESTIONS:
a. How to check if two given matrices are identical?
b. How will you check for an identity matrix?
c. Create a spiral matrix from the given array.
d. Find the longest route in the matrix.
e. Count all paths in a matrix from first cell to last cell
EXPERIMENT 2
AIM:
Write a program to perform addition of two complex numbers using constructor overloading.
The first constructor which takes no argument is used to create objects which are not initial-
ized, second which takes one argument is used to initialize real and imag parts to equal values
and third which takes two argument is used to initialized real and imag to two different val-
ues.
THEORY:
Constructor overloading means having more than one constructor with the same name. Con-
structors are methods invoked when an object is created. You must use the same name for all
the constructors which is the class name. This is done by declaration the constructor with a
different number of arguments.
ALGORITHM:
Step 1: Create a class Complex.
Step 2: Declare real and imaginary members.
Step 3: Create constructor to accept real and imaginary part.
Step 4 Defining add () method for adding two complex number
a. Creating temporary variable.
b. Adding real part of complex numbers.
c. Adding Imaginary part of complex numbers.
d. Return sum
Step 7: Stop the program.
VIVA QUESTIONS:
a. What is virtual Constructor? Explain with example?
b. Explain the order in which constructors are called when object of derived class
is created?
c. What are restrictions applied to constructor and destructor?
d. What is copy constructor? What is its use
e. What is significance of destructor in the program?
EXPERIMENT 3
AIM:
Write a program to find the greater of two given numbers in two different classes using friend
function.
THEORY:
A friend function can be granted special access to private and protected members of a class
in C++. They are the non-member functions that can access and manipulate the private and
protected members of the class for they are declared as friends.
ALGORITHM:
Step 1: Create two class A and class B.
Step 2: Create a friend function greatest common to both class A and class B.
Step 3: Define greatest function having objects of both class as argument:
void greatest(A a1,B b1)
{
if(a1.number>b1.number)
{
cout<<"\n Number in class A is greatest i.e. "<<a1.number;
}
else if(a1.number<b1.number)
{
cout<<"\n Number in class B is greatest i.e. "<<b1.number;
}
else
{
cout<<"\n Number in both classes are equal";
}
}
Step 4: Inside main take values for both numbers (belong to class A and class B).
Step 5: Call greatest function.
Step 6: Return greatest number.
Step 7: Stop the program.
VIVA QUESTIONS:
AIM:
Implement a class string containing the following functions:
a. Overload + operator to carry out the concatenation of strings.
b. Overload = operator to carry out string copy.
c. Overload <= operator to carry out the comparison of strings.
d. Function to display the length of a string.
e. Function tolower( ) to convert upper case letters to lower case.
f. Function toupper( ) to convert lower case letters to upper case.
THEORY:
Function overloading is a feature of object-oriented programming where two or more func-
tions can have the same name but different parameters. When a function name is overloaded
with different jobs it is called Function Overloading. In Function Overloading “Function”
name should be the same and the arguments should be different.
Operator overloading is a compile-time polymorphism. It is an idea of giving special mean-
ing to an existing operator in C++ without changing its original meaning.
ALGORITHM:
Step 1: Class Definition- Define a class named String that will encapsulate the string data
and its operations.
Step 2: Constructor- Implement a constructor that takes an initial string as a parameter and
initializes the internal string variable with it.
Step 3: Overload + operator to concatenate two String objects. Inside the operator
overloading method, concatenate the two strings values and return a new String object
with the result
Step 4: Overload = Operator for String Copy to copy one String object into another. Inside
the operator overloading method, assign the value of the right-hand side String to the left-
hand side String.
Step 5: Overload <= Operator for Comparison to compare two String objects. Inside the
operator overloading method, compare the values of the two String objects and return True
if the left-hand side is less than or equal to the right-hand side, and False otherwise.
Step 6: Function to Display Length- Implement a method (function) within the class to
calculate and return the length of the string. This can be done by counting the number of
characters in the string.
Step 7: Function to Convert to Lowercase (tolower)- Implement a method (function) to
convert all uppercase letters in the string to lowercase. You can iterate through the charac-
ters of the string and use the lower () function to transform them.
Step 8: Function to Convert to Uppercase (toupper)- Implement a method (function) to
convert all lowercase letters in the string to uppercase. You can iterate through the charac-
ters of the string and use the upper () function to transform them.
Step 9: Stop Algorithm.
VIVA QUESTIONS:
a. Explain overloading unary operator.
b. Explain difference between overloaded function and overridden function?
c. How to declare operator function?
d. In case of non- static member functions how many maximum object argu-
ments a unary operator overloaded function can take?
e. What is operator overloading in C++?
EXPERIMENT 5
AIM:
Create a class called LIST with two pure virtual function store () and retrieve (). To store a
value call store and to retrieve call retrieve function. Derive two classes stack and queue from
it and override store and retrieve.
THEORY:
A pure virtual function (or abstract function) in C++ is a virtual function for which we can
have an implementation, but we must override that function in the derived class, otherwise,
the derived class will also become an abstract class. A pure virtual function is declared by
assigning 0 in the declaration.
ALGORITHM:
Define an Abstract Base Class - LIST
Create a base class named LIST.
Declare two pure virtual functions within LIST: store() and retrieve(). These func-
tions will serve as interfaces to store and retrieve values.
Derive Stack Class from LIST:
Create a derived class named Stack that inherits from the LIST base class.
Override the store() function in the Stack class to implement storing values for a
stack.
Override the retrieve() function in the Stack class to implement retrieving values
for a stack.
Derive Queue Class from LIST:
Create another derived class named Queue that also inherits from the LIST base
class.
Override the store() function in the Queue class to implement storing values for a
queue.
Override the retrieve() function in the Queue class to implement retrieving values
for a queue.
Implement store() and retrieve() Functions in Derived Classes:
In the Stack class, the store() function should push values onto the stack, and the
retrieve() function should pop values from the stack.
In the Queue class, the store() function should enqueue values, and the retrieve()
function should dequeue values.
By following this algorithm, you will have created an abstract base class LIST with two pure
virtual functions that define the interface for storing and retrieving values. You will then derive
two classes, Stack and Queue, from the base class and override the store() and retrieve() func-
tions to implement the specific behavior for stacks and queues.
VIVA QUESTIONS:
a. What is a virtual function in C++?
b. Why are virtual functions used in object-oriented programming?
c. How is a virtual function different from a regular member function in a class?
d. Can a constructor or destructor be declared as a virtual function? Why or why
not?
e. How is function overriding related to virtual functions?
EXPERIMENT 6
AIM:
Write a program to define the function template for calculating the square of given numbers
with different data types.
THEORY:
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data
type as a parameter so that we do not need to write the same code for different data types.
For example, a software company may need to sort () for different data types. Rather than
writing and maintaining multiple codes, we can write one sort () and pass the datatype as a
parameter.
ALGORITHM:
Define the Function Template:
Start by declaring a function template with the keyword template followed by
the template parameter.
Define the function with a return type and parameters using the template pa-
rameter.
Template Parameter:
Choose a template parameter name, commonly denoted as T, to represent the
data type for which the square will be calculated.
Function Definition:
Inside the function template, define the function with the chosen template pa-
rameter.
Use the template parameter for the function parameter type to allow flexibility
for different data types.
Calculate Square:
Within the function body, calculate the square of the given number using the
formula value * value.
Function Call:
In your program, when you call the function, provide the appropriate data type
for the template parameter.
AIM:
Write a program to demonstrate the use of special functions, constructors, and destructor in
the class template. The program is used to find the bigger of two entered numbers.
THEORY:
The default constructors, destructors, copy constructors, and copy assignment operators are
special member functions. These functions create, destroy, convert, initialize, and copy class
objects.
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor
in C++ has the same name as the class or structure. It constructs the values i.e. provides data
for the object which is why it is known as constructor.
Destructor is an instance member function that is invoked automatically whenever an object
is going to be destroyed. Meaning, a destructor is the last function that is going to be called
before an object is destroyed.
ALGORITHM:
Class Template Definition:
Start by defining a class template named BiggerFinder that takes a template
parameter T for the data type.
Define Constructor:
Define a constructor that takes two parameters of type T and initializes the private
data members with the provided values.
Destructor:
Implement a destructor to perform any necessary cleanup. This is optional but can be
used to release resources.
VIVA QUESTIONS:
a. What is the purpose of a constructor in a class template?
b. How is the constructor declared and defined in a class template for finding the
bigger of two numbers?
c. Why use a class template for finding the bigger of two numbers?
d. What is the purpose of a destructor in the class template?
e. How is the destructor declared and defined in the class template?
EXPERIMENT 8
AIM:
Write a program to perform the deletion of white spaces such as horizontal tab, vertical tab,
space, line feed, new line and carriage return from a text file and store the contents of the file
without the white spaces on another file.
THEORY:
By default, there are six types of whitespace characters - space, line feed, horizontal tab, ver-
tical tab, carriage return, and form feed. We can write programs to remove whitespace from a
string in C++. These programs include the std::remove_if function, the std::regrex_re-
place function, and the boost library.
.
ALGORITHM:
Open Input File:
Open the input text file in read mode.
Close Files:
Close both the input and output files.
VIVA QUESTIONS:
a. What is the purpose of deleting white spaces from a text file?
b. Which white space characters are typically targeted for deletion in this process?
c. Why is it important to open the files in different modes (read and write) during this
process?
d. Why is the check for white space essential in the iteration process?
e. How does the algorithm handle the end of the input file?
EXPERIMENT 9
AIM:
Write a program to read the class object of student info such as name, age, sex, height, and
weight from the keyboard and to store them on a specified file using read () and write ()
functions. Again, the same file is opened for reading and displaying the contents of the file
on the screen.
THEORY:
File handling is used to store data permanently in a computer. Using file handling we can
store our data in secondary memory (Hard disk). Following operations can be performed
with file:
a) Naming a file
b) Opening a file
c) Writing data into the file
d) Reading data from the file
e) Closing a file.
ALGORITHM:
Define a Class for Student Information:
Create a class named StudentInfo with attributes such as name, age, sex, height, and
weight.
Close File.
VIVA QUESTIONS:
a. What is the purpose of the program you have written?
b. Explain the role of the read () function in your program.
c. How does the write () function work in this program?
d. What happens if the specified file is not accessible or does not exist during the write
operation?
e. Can you describe the process of reading data from the file using the read () function?
EXPERIMENT 10
AIM:
Write a program to raise an exception if any attempt is made to refer to an element whose
index is beyond the array size.
THEORY:
One of the advantages of C++ over C is Exception Handling. Exceptions are runtime anom-
alies or abnormal conditions that a program encounters during its execution. There are two
types of exceptions: a) Synchronous, b) Asynchronous (i.e., exceptions which are beyond the
program’s control, such as disc failure, keyboard interrupts etc.). C++ provides the following
specialized keywords for this purpose:
try: Represents a block of code that can throw an exception.
catch: Represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws but
does not handle itself.
ALGORITHM:
Initialize Array:
Declare an array and initialize it with the desired size.
EXPERIMENT 1
AIM:
Write a program to illustrate how template function can be overloaded.
THEORY:
Template background information has been given already.
ALGORITHM:
Define the First Template Function:
Start by defining a template function named printElement that takes a single parame-
ter of type T and prints it.
Function Calls:
In your program, call the template function with different data types to demonstrate
the overloading.// Calls the generic template function
Print Char: A Generic Print: Hello
VIVA QUESTIONS:
a. How template helps in real life?
b. What are the advantages of template overloading?
c. Give real life example where we can make use of function overloading?
d. Differentiate between function overloading and template overloading?
e. Why is template known as generic programming technique?
EXPERIMENT 2
AIM:
Write a program that simulates a simple banking system with multiple account types, transac-
tions, and error handling.
THEORY:
It will use almost all OOPS concepts.
ALGORITHM:
Define Account Classes:
Create base classes like Account and derived classes such as SavingsAccount, Check-
ingAccount, and LoanAccount. Each class should have attributes like account num-
ber, balance, and relevant methods.
Implement Transactions:
Include transaction methods like deposit, withdraw, and transfer in each account type.
Ensure that these methods update the account balance accordingly.
Error Handling:
Implement robust error handling mechanisms. For instance, handle insufficient funds
during withdrawals, check if the account exists before transferring, and validate user
input.
User Interface:
Create a user interface for interacting with the banking system. Utilize a menu system
that allows users to perform operations like creating accounts, making transactions,
and checking balances.
Note:
This is a broad overview, and the actual implementation may involve creating various
classes, error-checking mechanisms, and a well-designed user interface. You can add
additional features like interest calculation, account history, or security measures
based on your requirements.
VIVA QUESTIONS:
a. What is the purpose of the program you have described?
b. Why is it important to have multiple account types in the banking system sim-
ulation?
c. Can you explain the role of the Account base class and its derived classes in
the program?
d. How are transactions implemented in the program?
e. What kind of error handling mechanisms are included in the program?
f. Can you suggest additional features that could be added to enhance the bank-
ing system simulation?
g. What could be potential challenges or complexities in implementing a more
realistic banking system simulation?
EXPERIMENT 3
AIM:
C++ program that models a simplified library management system using object-oriented pro-
gramming principles?
THEORY:
It will use almost all OOPS concepts.
ALGORITHM:
Define Classes:
Create classes such as Book, Library, and Member to represent entities in the library
system. Each class should have attributes and methods that capture their functionali-
ties.
Implement Inheritance:
Utilize inheritance to represent a hierarchy. For example, a Book class may be a base
class, and derived classes like FictionBook and NonFictionBook inherit from it.
Use Polymorphism:
Implement polymorphism by allowing functions to operate on objects of different
types. For instance, a function to display book information should work for both fic-
tion and non-fiction books.
Handle Transactions:
Develop methods to handle library transactions, such as checking out and returning
books. Ensure proper updates to book availability and member records.
1. Incorporate Encapsulation:
Encapsulate data by making attributes private and providing public methods for ac-
cessing and modifying them. This enhances data integrity and security.
Note:
• This program is a comprehensive example that covers various object-oriented pro-
gramming principles, including inheritance, polymorphism, encapsulation, file I/O,
and exception handling.
VIVA QUESTIONS:
a. What is the purpose of the library management system program you've de-
scribed?
b. Explain the concept of inheritance in the context of your program.
c. How is polymorphism implemented in your program, and why is it beneficial?
d. Can you provide an example of encapsulation in your program?
e. How does the program handle library transactions, such as checking out and
returning books?
f. Explain the role of file I/O in your program.
g. How is exception handling incorporated in the program, and why is it im-
portant?
h. Describe the user interface of the library management system.
i. What advantages does using object-oriented programming principles provide
for this library management system?