Updated OOPs Lab Manual 2024
Updated OOPs Lab Manual 2024
Laboratory Manual
University Strives to
• Pursue excellence in teaching, learning and scholarship.
• Prepare students for leadership through enlightened learning partnerships with faculty
mentors and the community.
• Support faculty and other scholars in pursuing world-class research: clinical, theoretical,
empirical, experiential and foster creative endeavour.
• Promote and preserve academic freedom, diversity, equality, harmony and justice.
• Develop mastery of disciplines and professions and instil confidence among its key
constituents in their application for a future of meaningful pursuits and productive work in
the service of humanity.
• Channelise faculty and student talent for professionally related service to the university,
the community and society at large.
2
Core Values
• Uncompromising Academic Integrity.
• Scholarly work and continuous self-improvement.
• Encouraging and building student ability, character and creativity.
• Pride in Self, University and the Community.
• Leadership, Service, Philanthropy, Social Justice, and Entrepreneurship.
VISION:
To be a technical institution of repute nationally and internationally in higher learning
and research and to produce creative solutions to societal needs.
MISSION:
To provide every individual with a conducive environment suitable to achieve career
goals, with a strong emphasis on personality development, and to offer resources to the
academically inclined, to gain quality education in all spheres of engineering, applied
sciences and management, without compromising the quality and code of ethics to each
student of the Institution.
3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION:
Envisions to develop world class Engineers, researchers, and entrepreneurs in the field
of Computer Science & Information Technology driven by scientific curriculum
research, and experiential learning that will enable students to solve real world
problems.
MISSION:
• To impart critical thinking, humanistic and scientific inquiry in disciplinary and
interdisciplinary competencies and skills to solve-real world challenges.
• To provide an environment of continuous learning and improvement for students,
faculty members, and other stakeholders by instilling a culture of entrepreneurial
spirit through academic and research collaborations within university and across
national and international institutions of repute.
• To create highly skilled graduates with potential, to design and develop software
systems using innovative approaches in programming and problem solving
PROGRAM DETAILS
PEO1: Apply critical thinking to design, develop, analyze and implement solutions
to complex problems in computer science and engineering.
PEO2: Effectively deliver technical ideas and collaborate with multidisciplinary
teams to address societal needs and contribute to the advancement of technology.
PEO3: Engage in innovative practices, entrepreneurial endeavors, or technology-
based startups, contributing to the development of new products, services, or
solutions that address societal needs and challenges.
4
PROGRAM OUTCOMES
PO2. Problem analysis: Identify, formulate, research literature, and analyse complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues, and the consequent responsibilities relevant to the
professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9. Individual and teamwork: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
5
PO12. Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
SO1: an ability to identify, formulate, and solve complex engineering problems by applying
principles of engineering, science, and mathematics.
SO2: an ability to apply engineering design to produce solutions that meet specified needs with
consideration of public health, safety, and welfare, as well as global, cultural, social,
environmental, and economic factors.
SO4: an ability to recognize ethical and professional responsibilities in engineering situations and
make informed judgments, which must consider the impact of engineering solutions in global,
economic, environmental, and societal contexts.
SO7: an ability to acquire and apply new knowledge as needed, using appropriate
learning strategies
6
OBJECTIVES OF THE LAB
The objective of this lab is to understand and implement the core concepts of Object-Oriented
Programming (OOP) in C++. By the end of this lab, students should be able to:
LAB SETUP
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
2: Inheritance
• Objective: Understand how to reuse and extend existing classes using inheritance.
• Description:
o Create a Person class with attributes for name and age, and methods to set and get
these attributes.
7
o Create a student class that inherits from Person and adds additional attributes for
studentID and major.
o Override the displayInfo method to include student-specific information.
• Skills Gained: Implementation of inheritance, method overriding, and reusability of code.
3: Polymorphism
• Objective: Learn how to use polymorphism to design flexible and reusable code.
• Description:
o Using the Person and Student classes, demonstrate polymorphic behavior.
o Create a function printPersonInfo that takes a Person pointer and calls the
displayInfo method.
o Show how this function can be used with both Person and Student objects.
• Skills Gained: Understanding of polymorphism, virtual functions, and dynamic binding.
4: Encapsulation
5: Function Templates
8
6: Class Templates
7: Exception Handling
8: File Handling
• Objective: Understand how to use file handling to read from and write to files.
• Description:
o Create a program to write user input to a file.
o Create a program to read data from a file and display it on the console.
o Implement error checking to ensure the file operations are successful.
• Skills Gained: Understanding of file handling, stream operations, and error checking.
9
SAFETY PRECAUTIONS AND GUIDELINES
• You may use the computers in the lab only when a teacher is present.
• Please place your bags at the front of the lab.
• Keep the lab clean and neat at all times.
• Use only the computer you are assigned to.
• Report any hardware fault immediately to your teacher. Never attempt to dismantle the
different parts of the computer.
• Each student must log in to his/her account. No sharing of accounts is permitted.
• The computers are for your academic use. Playing computer games for entertainment is
strictly not allowed.
• Shut down the computer properly after use.
• Do not charge your personal mobile devices in the lab.
Syllabus
Course Title Object Oriented Programming CREDITS
Core/Elective/ L 2-0-2-
T P S C CH
Course Code 3 CS 1005 Course Category Ability 0-3-4
Enhancement 2 0 2 0 3 4
Course
Dr R Rajasekar, Professor/CSE
Coordinator
This course provides a comprehensive introduction to Object-Oriented Programming (OOP)
using C++, a powerful and widely used programming language in both academic and industry
Course
settings. The course is designed to equip students with the fundamental concepts and
Description
techniques of OOP and to develop their ability to design and implement robust, maintainable,
and efficient C++ programs.
1. Understand the basic building blocks of programming, such as variables, data types,
operators, expressions, and control flow statements.
2. Design and implement classes and objects.
Course
3. Learn how to use polymorphism to achieve dynamic binding and virtual function calls.
Objectives
4. Learn how to use arrays and strings to store and manipulate data.
5. Understand how to use templates to create generic classes and functions that can work
with different data types.
10
Bloom’s
Course
CO Statement Taxonomy
Outcome
Level
1 Understand and apply the principles of object-oriented programming. 2
2 Implement Iterative and Conditional Control Structures: 3
3 Design and implement C++ programs using classes and objects. 3
4 Understand and Apply Inheritance, Operator Overloading. 3
Utilize virtual functions for dynamic binding and friend functions for 3
5
privileged access across classes.
Course Syllabus
Module Name Contact Hours: 45
Control Statements and Functions: Loops: For loop – while loop & do loop, Decisions: If-
if else, switch, control statements, Array and Strings: Array Fundamentals and string
Module -II handling, Functions: Function prototyping, Passing arguments to functions, Returning values
from functions ,Reference arguments, overloaded functions ,Recursion, Inline functions,
default arguments ,scope and storage class, Returning by reference
Class and objects: A simple class, Modifiers or access specifiers, C++ objects, C++ objects
as data types, Constructor and destructor: constructor definition, types-parameterized, Object
Module -III as function arguments, Overloaded constructors, Copy constructors, returning objects from
functions, destructors, Structures and classes ,Static class data, constant classes , arrays as
class members ,arrays of objects.
11
Inheritance: Derived class and Base class, types of Inheritance - single, multiple, multilevel,
hierarchical and hybrid derived class constructors, function overriding and Aggregation.
Other Functions: Virtual Functions, Friend Functions, Static Functions, and. Operator
Module -IV Overloading: Unary Operators, Binary Operators overloading, Overloading assignment
Operators, Pointer Pointers: address and pointers, Pointers and arrays, pointers and functions,
this pointer, new and delete operator, pointers to objects, pointers to pointer
Practical Syllabus
Experiment Name
No.
Create a Structure STUDENT with the fields name, roll_num, marks (marks in 5 different
subjects), total and average and write the functions to perform following operations:
a. Write program to implement function handling in C++ to add two numbers sign with
arguments and with return values.
3.
b) Write a C++ program to compute the area of Square, Circle, Triangle and Rectangle using
function overloading concept.
12
a. write a program in C++ to prepare a student Record using class and object.
4.
b. writes a program to Implement of constructors.
a) Write a C++ program to implement single inheritance using employee 1 as base class and
employee 2 as derived class. Calculate and display the gross salary for both the employee
class object, considering sales percentage for employee 2 class object.
5.
b) Write a C++ program to create a class called student with data members username, id and
age using inheritance. Create the class ug_students and pg_students having data members
called semester, fee_stipend, CGPA. Enter data for at least 10 students. Find the semester wise
average age for all ug and pg students.
a) Write a C++ program to demonstrate hierarchical inheritance for Employee class as base
class (name and e_id as data member) and derived classes as Manager Class (title and dues as
data member), Scientist class(pubs as data member) and Laborer class(no data member). Read
6.
and display the data for multiple derived class objects.
13
Program 1: Abstract Classes and Pure Virtual Functions
An abstract class in C++ is a class that cannot be instantiated and is designed to be inherited from. It usually
contains at least one pure virtual function.
Multiple inheritance allows a class to inherit from more than one base class.
14
CO-PO MAPPING
Cours P P P P P P P P P PO PO PO PS PS PS
e O O O O O O O O O 10 11 12 O1 O2 O3
Outco 1 2 3 4 5 6 7 8 9
mes
CO1 3 3 3 2 2 2 2 3
CO2 3 3 3 2 2 2 3 2
CO3 3 3 3 2 2 2 2 2
CO4 3 3 3 2 2 2 2 2 2
CO5 3 3 3 2 2 2 2 2 2 1
CO-SO MAPPING:
Course Student Outcomes (EAC) Student Outcomes (CAC)
Outcomes SO1 SO2 SO3 SO4 SO5 SO6 SO7 SO1 SO2 SO3 SO4 SO5
CO1 1 2
CO2 1 2 1 1 1
CO3 2 2 2 2 1 2
CO4 2 2 2 2 2
CO5 2 2 2 1 2 2
LIST OF EXPERIMENTS
Sl.No Name of Experiment/Assignment Equipment/Tool/Consumables Page
Required for conduction No.
1. Create a Structure STUDENT with the fields At least 8 GB RAM, Intel i5 or
name, roll_num, marks (marks in 5 different equivalent processor, 500 GB
subjects), total and average and write the functions HDD/SSD / Visual Studio,
Code:Blocks, CLion, Eclipse. /
to perform following operations:
GCC (GNU Compiler
Collection), Clang, Microsoft
1. Input the details of n students. Visual C++.
19-22
2. Calculate the total and average marks for
each student.
15
2 Create a structure EMPLOYEE with the field’s
employee name, id, grade, basic, da, hra, gross
salary, net salary. Input the details of n employees
and calculate the gross salary, net salary and tax
paid for each of them. Write the functions to
perform the following operations:
16
b) Write a C++ program to create a class called
student with data members username, id and age
using inheritance. Create the class ug_students and
pg_students having data members called semester,
40-42
fee_stipend, CGPA. Enter data for at least 10
students. Find the semester wise average age for
all ug and pg students.
17
money, withdrawing money, and checking the
account balance.
Mini Project ( Team Work)
1) Design a system for a library management application using classes in C++. Include classes
for Book, Library, and Member. Each Book should have properties such as title, author,
ISBN, and availability status. The library class should manage a collection of books and
allow operations like adding a book, lending a book to a member, and returning a book.
The Member class should represent library members with properties like name, member
ID, and borrowed books. (BTL 6)
3) Design a generic stack data structure using templates in C++. Implement the stack using
an array-based approach and provide methods for pushing, popping, checking if the stack
is empty, and retrieving the top element. Test the stack implementation with different data
types (e.g., int, double, string) to demonstrate its reusability and flexibility using templates.
(BTL 6)
Suggested Complex problems for proficient Learners linked with real world
problems/Applications.
Sl.No Problem Statement Linked Page No
Experiment No.
1 Enhanced Input Handling and 4-5 25
Validation-
2 Advanced Sorting Techniques 8-9 50
18
Exp. No. 1 Title of the Experiment Date:
Create a Structure STUDENT with the fields name, roll_num, marks (marks in 5 different
subjects), total and average and write the functions to perform following operations:
Aim: The aim of this experiment is to create a structure named STUDENT with the fields name,
roll_num, marks (marks in 5 different subjects), total, and average, and to write functions that
perform the operations
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Algorithm:
• Structure: STUDENT
o Fields: name, roll_num, marks [5], total, average
19
▪ For j from 0 to 4:
▪ Read students[i]. marks[j]
• Function: main ()
o Read n
o Declare STUDENT students[n]
o Call inputDetails(students, n)
20
o Call calculateTotalAndAverage(students, n)
o Call sortStudents(students, n)
o Call displayDetails(students, n)
Sample Output/Result
Enter the number of students: 3
Enter details for student 1:
Name: Alice
Roll Number: 102
Enter marks in 5 subjects: 85 90 78 92 88
Enter details for student 2:
Name: Bob
Roll Number: 101
Enter marks in 5 subjects: 75 80 70 82 77
Enter details for student 3:
Name: Charlie
Roll Number: 103
Enter marks in 5 subjects: 95 92 89 94 90
Student Details (sorted by roll number):
Name: Bob, Roll Number: 101, Total Marks: 384, Average Marks: 76.8
Name: Alice, Roll Number: 102, Total Marks: 433, Average Marks: 86.6
Name: Charlie, Roll Number: 103, Total Marks: 460, Average Marks: 92
21
Inferences:
creating a structure involves defining a user-defined data type that can hold both data members
(variables) and member functions (methods). Here’s an outline of the inferences or key aspects
related to creating a structure in OOP with C++
Viva Questions:
1. What is the purpose of using a structure in C++?
2. Explain the components of the STUDENT structure you have defined for this experiment.
3. How do you input the details of n students using functions in your program?
4. Can you explain the importance of sorting students based on roll numbers in a real-world
scenario?
22
Exp. No. 2 Title of the Experiment Date:
Create a structure EMPLOYEE with the field’s employee name, id, grade, basic, da, hra, gross
salary, net salary. Input the details of n employees and calculate the gross salary, net salary and
tax paid for each of them. Write the functions to perform the following operations:
2. Display the details of all the employees of a given grade and sort based on employee id.
Aim: The program that manages employee records using a structured approach. The program will
define a structure EMPLOYEE with fields for employee details and salary components. Operations
will include sorting employees based on ID, displaying employees by grade with sorting, and
identifying employees with the highest and lowest tax payments.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
23
• Output: Gross salary calculation for each employee
• Main Function:
o Initialize array of EMPLOYEE structures.
o Call functions sequentially to input details, calculate salaries and tax, perform
sorting, and display results based on user requirements.
1. Employee 1:
o Name: John Doe
o ID: 101
24
o Grade: A
o Basic Salary: 50000
o DA: 8000
o HRA: 6000
2. Employee 2:
o Name: Jane Smith
o ID: 102
o Grade: B
o Basic Salary: 45000
o DA: 7000
o HRA: 5000
3. Employee 3:
o Name: Michael Johnson
o ID: 103
o Grade: A
o Basic Salary: 48000
o DA: 7500
o HRA: 5500
25
Inferences:
Creating a structure for an Employee in C++ involves defining a user-defined data type that
encapsulates various attributes and behaviors related to an employee
Viva Questions:
1. Explain the significance of using a structure in C++ to represent an EMPLOYEE. How does
using a structure facilitate the organization and manipulation of employee data in this program?
2. Discuss the role of constructors and member functions in the EMPLOYEE structure.
3. Explain how the program sorts employee details based on ID. What sorting algorithm would
you use, and why?
4. What factors determine the amount of tax paid by an employee, and how does the program
ensure accuracy in tax calculation?
26
Exp. No. 3 a. Title of the Experiment Date:
Write program to implement function handling in C++ to add two numbers sign with
arguments and with return values
Aim: Write a C++ program that implements function handling to add two numbers, using function
arguments and returning the sum as a result.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm: Adding Two Numbers Using Function Handling in C++
1. Start:
2. Declare Function Prototype:
o Declare a function prototype int addNumbers(int num1, int num2); to specify the
function name (addNumbers), parameters (num1 and num2 of type int), and return
type (int).
3. Define Main Function:
o Declare integer variables num1, num2, and sum.
o Output a prompt to enter the first number (num1).
o Input num1 from the user.
o Output a prompt to enter the second number (num2).
o Input num2 from the user.
o Call the function addNumbers(num1, num2) and assign its return value to sum.
o Output the result (sum) along with a descriptive message.
4. Define Function addNumbers:
o Start the function definition int addNumbers(int num1, int num2).
o Declare an integer variable result.
o Compute the sum of num1 and num2 and store it in result.
o Return result.
5. End
27
Input
Enter first number: 25
Enter second number: 37
Output
Sum of 25 and 37 is: 62
Inferences:
The key inferences of Function definition and function Argument and Return , Encapsulation,
Function Overloading.
Viva Questions:
1. What is the purpose of using functions in C++ programming?
2. Explain the concept of function prototyping in C++. Why is it necessary?
3. How does the addNumbers function in your program work?
4. Discuss the advantages of using function return values in C++ programs.
28
Exp. No. 3 b. Title of the Experiment Date:
Write a C++ program to compute the area of Square, Circle, Triangle and Rectangle using function
overloading concept.
Aim: Write a C++ program to compute the area of geometric shapes (Square, Circle, Triangle,
and Rectangle) using function overloading concept, where each shape's area calculation is
encapsulated in a separate function with the same name but different parameter lists based on the
shape's requirements.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start:
Step 2: Include necessary header files:
• Declare function prototypes for each shape's area calculation using function overloading:
o double calculateArea(int sideLength); for Square
o double calculateArea(double radius); for Circle
o double calculateArea(int base, int height); for Triangle
o double calculateArea(int length, int width); for Rectangle
• Declare variables:
o int choice to store user's shape selection.
o Variables for dimensions (sideLength, radius, base, height, length, width) based on
shape selected.
• Display menu to choose a shape (Square, Circle, Triangle, Rectangle).
29
• Read user's choice (choice).
• Use switch statement on choice:
o Case 1: Calculate area of Square:
▪ Prompt user for sideLength.
▪ Call calculateArea(sideLength) and print the result.
o Case 2: Calculate area of Circle:
▪ Prompt user for radius.
▪ Call calculateArea(radius) and print the result.
o Case 3: Calculate area of Triangle:
▪ Prompt user for base and height.
▪ Call calculateArea(base, height) and print the result.
o Case 4: Calculate area of Rectangle:
▪ Prompt user for length and width.
▪ Call calculateArea(length, width) and print the result.
o Default: Display error message for invalid choice.
Step 6: End.
30
Inferences:
• In C++, function overloading allows you to define multiple functions with the same name
but with different parameter lists. This concept can be effectively used to compute the area
of different geometric shapes such as Square, Circle, Triangle, and Rectangle
Viva Questions:
1. What is function overloading in C++? How does it apply to the program you've written?
2. How does the main function interact with the calculateArea functions to compute the
area of different shapes?
3. What are the advantages of using function overloading in this program compared to
using separate functions for each shape's area calculation?
4. Can you explain a scenario where function overloading might lead to ambiguity? How
can such issues be resolved in C++?
31
Exp. No. 4 a. Title of the Experiment Date:
write a program in C++ to prepare a student Record using class and object.
Aim:
Write a program in C++ to implement a student record system using class and object concepts,
where each student's information (such as name, roll number, marks) is encapsulated within a class.
Utilize object-oriented programming principles to manage and display student records efficiently.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start:
Step 2: Include necessary header files:
• Define a class Student with private data members (name, rollNumber, marks, etc.) to
encapsulate student information.
• Include public member functions (methods) to set and get student details, calculate grades,
display student information, etc.
• Optionally, include constructors to initialize objects with default values or user-provided
data.
32
• Optionally, allow user input to dynamically add or update student information,
demonstrating the flexibility of class-based data management.
• Implement methods within the Student class to manage student data securely (e.g.,
validation of input data, handling exceptions).
• Utilize access specifiers (public, private, protected) to control access to class members,
ensuring data integrity and security.
• Implement a user-friendly interface in the main function to interact with the student record
system.
• Allow users to input student details, perform operations like adding, deleting, or updating
records, and display student information in a structured format.
Step 7: End
Student 2 Details:
Name: Jane Smith
Roll Number: 102
Marks: 92.0
Inferences:
Creating a student record using classes and objects in C++ involves defining a class to encapsulate
student information and using objects of that class to represent individual student records. Here
are the key inferences and steps involved in preparing a student record using class and object in
C++
33
Viva Questions:
1. How does encapsulation contribute to the design of your student record program?
2. What are classes and objects in C++? How are they utilized in the context of your
program to manage student records?
3. iscuss the role of constructors in your student record program. How are they utilized,
and why are they important?
4. Discuss any OOP concepts such as inheritance or polymorphism that are applicable or
could be extended in your student record system.
34
Exp. No. 4 b. Title of the Experiment Date:
Aim:
Write a C++ program to implement constructors, demonstrating their role in initializing objects of
a class with default values and user-provided data. Explore the use of constructors to ensure object
initialization and prepare objects for further operations within the program.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start:
Step 2: Include necessary header files:
• Define a class Student with private data members (name, rollNumber, marks) to
encapsulate student information.
• Include constructors (default constructor and parameterized constructor) to initialize
objects (student1, student2, etc.) with default or user-provided data.
• Optionally, include other member functions (methods) to manipulate and display student
details.
35
o Set private data members (name, rollNumber, marks) with values provided as
parameters during object creation.
• In the main function or other relevant functions, create objects (student1, student2, etc.) of
the Student class using different constructors.
• Use object methods (display, etc.) to manipulate and display student details.
Step 6: Demonstration:
• Illustrate the usage of constructors to initialize objects (student1, student2) with default and
user-defined values.
• Display student details using object methods to verify correct initialization and operation
of the program.
Step 7: End.
Sample output / Result
Student 1 Details:
Name:
Roll Number: 0
Marks: 0
Student 2 Details:
Name: John Doe
Roll Number: 101
Marks: 85.5
36
Inferences:
Implementing constructors in a C++ program allows you to initialize objects of a class when they
are created. Constructors are special member functions that are automatically called when objects
of the class are instantiated
Viva Questions:
1. What are constructors in C++?
2. Explain the difference between a default constructor and a parameterized constructor.
3. How do constructors contribute to the principles of object-oriented programming
(OOP)?
4. Discuss scenarios where you might use different types of constructors (default,
parameterized) in a C++ program.
37
Exp. No. 5 a. Title of the Experiment Date:
Write a C++ program to implement single inheritance using employee 1 as base class and
employee 2 as derived class. Calculate and display the gross salary for both the employee class
object, considering sales percentage for employee 2 class object.
Aim:
Write a C++ program to demonstrate single inheritance using Employee1 as the base class and
Employee2 as the derived class. Calculate and display the gross salary for both Employee1 and
Employee2 class objects, considering a sales percentage for the Employee2 class object.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
• Declare a private data member salesPercentage to store the sales bonus percentage.
• Implement a parameterized constructor to initialize data members of both base
(Employee1) and derived class (Employee2).
38
• Override the calculateGrossSalary() method inherited from Employee1 to include the sales
bonus (basicSalary + allowances + (basicSalary * salesPercentage / 100)).
Step 6: End
Inferences:
• implementing single inheritance in C++ involves creating a base class (parent class) and a
derived class (child class) where the derived class inherits properties and behaviours from
the base class. Here’s how you can implement this concept with Employee1 as the base
class and Employee2 as the derived class
Viva Questions:
1. What is single inheritance in C++?
2. Explain the concept of method overriding as demonstrated in your program. How does
Employee2 override the calculate Gross Salary() method inherited from Employee1?
3. How does polymorphism apply in the context of your program using single
inheritance?
4. Discuss the advantages of using inheritance in your program. How does it contribute
to code reuse and maintainability?
39
Exp. No. 5 b. Title of the Experiment Date:
Write a C++ program to create a class called student with data members username, id and age
using inheritance. Create the class ug_students and pg_students having data members called
semester, fee_stipend, CGPA. Enter data for at least 10 students. Find the semester wise average
age for all ug and pg students.
Aim:
Write a C++ program to create a class Student with data members username, id, and age, and
implement inheritance to derive classes ug_students and pg_students. ug_students and pg_students
will have additional data members semester, fee_stipend, and CGPA. Input data for at least 10
students, calculate and display the semester-wise average age for all ug_students and pg_students.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Algorithm:
• Declare a class Student with private data members username, id, and age.
• Provide public member functions:
o setData() to initialize username, id, and age.
o getAge() to retrieve the age of the student.
o displayData() to output username, id, and age.
40
o
CGPA: Cumulative Grade Point Average.
• Implement public member functions:
o setData() to initialize all data members including inherited ones.
o getSemester() to retrieve the semester number.
o displayData() to output all data members including inherited ones.
• Declare arrays or containers for at least 10 objects of type ug_students and pg_students.
• Loop to input data for each student object:
o Prompt and read username, id, age, semester, fee_stipend, and CGPA.
o Call setData() for each student object to set the respective data members.
• Initialize variables to accumulate total ages and count of students for each semester
(sum_age_semester, count_students_semester).
• Loop through each object in the arrays:
o Use getAge() and getSemester() to retrieve age and semester information.
o Accumulate age into sum_age_semester based on the semester of the current object.
o Increment count_students_semester for each student in the semester.
• Calculate average age for each semester (avg_age_semester = sum_age_semester /
count_students_semester).
• Output the semester-wise average ages.
Student 1:
ID: 101
Age: 20
Semester: 2
Fee/Stipend: 1500.0
CGPA: 8.2
Student 2:
41
ID: 102
Age: 21
Semester: 3
Fee/Stipend: 1800.0
CGPA: 7.9
Inferences:
In C++, using inheritance allows you to create a hierarchy of classes where a derived class inherits
characteristics (data members and member functions) from a base class. Let's create a scenario
where a Student class inherits from a base class Person, which includes data members username,
id, and age.
Viva Questions:
1. Explain how you implemented inheritance in your C++ program for student
management.
2. How did you ensure data encapsulation and access control in your program?
3. Describe the process of calculating semester-wise average age for both undergraduate
and postgraduate students in your program.
4. How would you modify your program to include additional functionality, such as
calculating GPA or handling more than 10 students?
42
Exp. No. 6a. Title of the Experiment Date:
Write a C++ program to demonstrate hierarchical inheritance for Employee class as base class
(name and e_id as data member) and derived classes as Manager Class (title and dues as data
member), Scientist class(pubs as data member) and Laborer class(no data member). Read and
display the data for multiple derived class objects.
Aim:
The aim of this C++ program is to demonstrate hierarchical inheritance using the Employee class
as the base class, with Manager, Scientist, and Laborer classes derived from it. The Employee class
includes name and e_id as data members. The derived classes (Manager, Scientist, Laborer) each
have their own additional data members (title and dues for Manager, pubs for Scientist, and no
additional data members for Laborer).
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1 : Start
• Declare a base class Employee with private data members name (string) and e_id (integer).
• Provide public member functions to set (setName, setEid) and get (getName, getEid) these
data members.
• Manager Class:
o Inherit publicly from Employee.
o Add private data members title (string) and dues (double).
43
o Provide public member functions to set (setTitle, setDues) and get (getTitle,
getDues) these data members.
• Scientist Class:
o Inherit publicly from Employee.
o Add private data member pubs (integer).
o Provide public member functions to set (setPubs) and get (getPubs) this data
member.
• Laborer Class:
o Inherit publicly from Employee.
o No additional data members.
• Declare and initialize objects of each derived class (Manager, Scientist, Laborer).
• Use member functions to set data for each object (name, employee ID, title, dues,
publications).
• Use member functions to get and display data for each object.
• Ensure that data from both the base class (Employee) and derived classes (Manager,
Scientist, Laborer) are displayed appropriately.
Step 6: End
Manager Details:
Dues: $1500.00
Scientist Details:
Publications: 5
44
Laborer Details:
Inferences:
Hierarchical inheritance in C++ involves creating a class hierarchy where multiple derived classes
inherit from a single base class. In this scenario, we'll create a Employee class as the base class,
and then derive two classes from it: Manager and possibly another derived class like Worker
(though not explicitly mentioned)
Viva Questions:
1. Explain the concept of hierarchical inheritance in object-oriented programming using the
example of your C++ program
2. Describe the role of polymorphism in your C++ program.
3. Discuss the importance of encapsulation in the Employee base class of your program
4. Explain the process of reading and displaying data for multiple derived class objects in
your C++ program.
45
Exp. No. 6b. Title of the Experiment Date:
Aim:
To develop a C++ program that defines a Distance class and implements methods to input, display,
and add three Distance objects, demonstrating the addition of distances in feet and inches
accurately.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
46
• Prompt the user to input distances for d1, d2, and d3.
• Use the addThreeDistances() method of d1 to compute the sum of d1, d2, and d3.
• Display the result using the displayDistance() method.
47
Inferences:
Adding three Distance class objects in C++ involves creating a class that represents distances and
overloading the + operator to allow addition of distances.
Viva Questions:
1. Can you explain how you designed the Distance class to handle feet and inches in your
program?
2. Describe the purpose of the addThreeDistances() method in your Distance class. How
does it work?
3. How did you ensure user input for distances is handled correctly in your program?
4. hat are the advantages of using a custom Distance class over directly using primitive
data types (like int and float) for representing distances in your program?
48
Exp. No. 7. Title of the Experiment Date:
write a C++ program that demonstrates multiple inheritance by creating a class that inherits from
two base classes
Aim:
To write a C++ program that demonstrates multiple inheritance by creating a derived class that
inherits from two base classes. The program should illustrate how multiple inheritance allows a
class to inherit properties and behaviors from more than one base class, showcasing the flexibility
and power of this object-oriented programming feature.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
• Create two base classes, let's name them Base1 and Base2, each with distinct member
variables and methods.
• Implement Base1 and Base2 with appropriate member variables and methods.
• Create a derived class, Derived, that inherits publicly from both Base1 and Base2.
49
• Implement the main() function where objects of the Derived class are created and their
member functions are called to demonstrate inheritance.
Inferences:
Multiple inheritance in C++ allows a derived class to inherit from more than one base class. This
feature enables a class to combine features and behaviours from multiple parent classes into a
single derived class.
Viva Questions:
1. What is multiple inheritance in C++? How does it differ from single inheritance?
2. Describe the structure of your program that demonstrates multiple inheritance with a
derived class inheriting from Base1 and Base2.
3. What are the advantages and potential pitfalls of using multiple inheritance in C++?
4. Discuss the design considerations when deciding to use multiple inheritance versus other
inheritance models
50
Exp. No. 8. Title of the Experiment Date:
Write a C++ program that computes the area of a triangle and rectangle using a pure virtual
function in a base class
Aim:
To develop a C++ program that demonstrates the use of abstract base classes and pure virtual
functions to compute the area of geometric shapes, specifically a triangle and a rectangle. The
program should illustrate inheritance, polymorphism, and abstraction by defining a base class with
a pure virtual function for area calculation, which is overridden in derived classes representing the
triangle and rectangle.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
• Create an abstract base class Shape with a pure virtual function virtual float calculateArea()
= 0;.
• This class will serve as the base for shapes like triangle and rectangle.
• Create derived classes Triangle and Rectangle that inherit publicly from the Shape base
class.
• Implement the calculateArea() function in each derived class to compute the area specific
to each shape
51
Step 4: Display Results:
• Display the calculated area for each shape using the overridden calculateArea() function
Base: 5
Height: 8
Length: 4
Breadth: 6
Inferences:
To compute the area of shapes like a triangle and rectangle using a pure virtual function in a base
class in C++, you would typically create an abstract base class with a pure virtual function for
calculating the area.
Viva Questions:
1. What is a pure virtual function in C++? How is it declared and used in the context of
abstract base classes?
2. How does polymorphism play a role in your program that calculates the area of a triangle
and rectangle using the Shape base class and derived classes like Triangle and Rectangle?
3. Describe the process of creating a new shape (e.g., a circle) in your program. What changes
would you make to incorporate a new shape while maintaining the existing structure?
4. Explain the importance of using an abstract base class (Shape) in your program design.
How does it promote code reusability and maintainability?
52
Exp. No. 9. Title of the Experiment Date:
write C++ program that swaps two numbers using the concept of a function template.
Aim:
To develop a C++ program that demonstrates the use of function templates to swap two numbers
of any data type. This program aims to illustrate the flexibility and reusability provided by function
templates in C++, allowing the swapping of integers, floats, doubles, or any other user-defined
data type without needing separate implementations for each type.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
Step 2: Define a function template swapNumbers that takes two parameters of type T (template
parameter).
• Declare variables of different types (int, float, double, etc.) to demonstrate the flexibility
of the function template.
• Prompt the user to enter values for the variables.
• Call the swapNumbers function template with appropriate arguments to swap the values.
• Display the swapped values to verify the correctness of the swap operation.
53
Step 6: End
First integer: 5
Second integer: 10
Swapped integers: 10 5
Inferences:
Swapping two numbers using a function template in C++ allows you to write a single function that
can work with different data types (like int, double, etc.) without having to overload the function
for each type.
Viva Questions:
1. What is a function template in C++? How does it differ from a regular function or a
function with function overloading?
2. How does the function template swapNumbers handle different data types (e.g., int,
float, double) seamlessly?
3. What are the advantages of using a function template over traditional function
overloading for implementing operations like swapping two numbers?
4. Explain the process of using the function template swapNumbers in a C++ program.
Provide a step-by-step explanation of how the template is instantiated and how the
swapping operation is performed for integers and floats.
54
Exp. No. 10a. Title of the Experiment Date:
Write a C++ program that overloads the binary + operator to add two Distance class objects.
Aim:
To develop a C++ program that demonstrates operator overloading by overloading the binary +
operator in the Distance class. This program aims to enable the addition of two Distance objects
using the overloaded operator, allowing for intuitive and natural addition of distance values
represented by objects of the Distance class.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
Step 2 : Define a class Distance with private data members:
Step 4: Implement the operator+ function outside the class using the Distance class declaration:
55
▪ Create a temporary Distance object.
▪ Calculate the sum of feet and inches for the objects d1 and d2.
▪ Return the temporary Distance object containing the sum.
Step 6: End
Inferences:
Overloading the binary + operator in C++ allows you to define custom addition behaviour for
objects of a class. In this case, we'll overload the + operator for adding two Distance class objects.
Viva Questions:
1. What is operator overloading in C++? How does it differ from function overloading?
2. Why is operator overloading useful in object-oriented programming? Provide specific
advantages of overloading the + operator for adding Distance class objects.
3. Describe the implementation of the Distance class used to demonstrate operator
overloading for adding distances.
4. Discuss the concept of operator precedence and associativity in C++. How does
operator overloading affect these concepts?
56
Exp. No. 10b. Title of the Experiment Date:
Write a C++ program to set duration and distance class objects by passing them as parameter to
friend function
Aim:
To develop a C++ program that demonstrates the usage of friend functions by defining a function
that sets values of duration and distance class objects, which are private members of their
respective classes. This program aims to showcase how friend functions can access and modify
private data members of multiple classes to achieve encapsulation while allowing specific access
for designated functions.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1: Start
Step 2: Define a Distance class with private data members:
• Declare a friend function void setValues(Distance& d, Duration& dur); inside the Distance
class declaration.
• Define appropriate constructors and any necessary member functions to initialize and
display Distance objects.
57
• Declare a friend function void setValues(Distance& d, Duration& dur); inside the Duration
class declaration.
• Define appropriate constructors and any necessary member functions to initialize and
display Duration objects.
Step 8: End
Inferences:
In C++, friend functions provide access to private and protected members of a class when external
functions need to interact closely with the class but aren't members of it. Here’s how you can
design a C++ program using friend functions to set data members of Duration and Distance class
objects
Viva Questions:
1. What is a friend function in C++?
2. How does it differ from member functions and ordinary non-member functions?
3. Why is encapsulation important in object-oriented programming?
4. How does the use of friend functions impact encapsulation in the context of the
program that sets duration and distance objects?
58
Exp. No. 11 Title of the Experiment Date:
write a C++ program that handles division by zero using exception handling mechanisms (try,
catch, and throw).
Aim:
To develop a C++ program that demonstrates the use of exception handling mechanisms (try,
catch, and throw) to gracefully handle the scenario of division by zero. This program aims to ensure
that the application does not crash when encountering a division operation where the denominator
is zero, by catching the exception and providing appropriate error handling or recovery steps.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step1 : Start
Step 2: Include necessary header files:
59
o Print an error message indicating division by zero occurred.
o Provide appropriate error handling or recovery steps (e.g., re-prompting user for
valid input).
Handling division by zero in C++ using exception handling involves using try, catch, and throw
mechanisms to detect and manage runtime errors
Viva Questions:
1. What is exception handling in C++?
2. How does it differ from traditional error-handling techniques using return codes or global
flags?
3. How does the program handle the scenario of division by zero using exception handling
mechanisms?
4. What are the benefits of using exception handling (try, catch, throw) in the provided
program?
60
Exp. No. 12 Title of the Experiment Date:
Write a C++ program to create a simple Bank Application that allows users to perform basic
operations such as creating an account, depositing money, withdrawing money, and checking the
account balance.
Aim:
To develop a C++ program that simulates a basic Bank Application where users can create
accounts, deposit funds, withdraw funds, and check their account balances. This program aims to
provide a user-friendly interface for managing banking operations through structured classes and
functions, ensuring data integrity and security while demonstrating fundamental concepts of
object-oriented programming and basic financial transactions.
Requirements:
• IDE: Any C++ IDE (e.g., Code: Blocks, C Lion, Visual Studio, etc.)
• Compiler: Any standard C++ compiler (e.g., GCC, Clang, MSVC, etc.)
Suggested Reading (Theoretical Background):
"The C++ Programming Language" by Bjarne Stroustrup: This is the authoritative guide written
by the creator of C++. It covers all aspects of the language from basics to advanced features.
Algorithm:
Step 1 : Start
Step 2 Include necessary header files:
• BankAccount: Represents each bank account with attributes such as account number,
account holder name, balance, etc.
61
Step 5: Implement the main function int main().
• Inside main:
• Declare variables to store user inputs and menu choices (choice, accountNumber, amount,
etc.).
• Use a loop to display a menu of options (create account, deposit, withdraw, check balance,
exit).
• Based on user choice, call appropriate methods of the BankAccount class to perform
operations.
• Validate user inputs (e.g., account number should be unique, withdraw amount should not
exceed balance).
• Use exception handling (try, catch) to manage scenarios like insufficient balance during
withdrawal.
62
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 2
Enter Account Number: 1001
Enter Deposit Amount: 1500
Deposit successful. Current balance: $6500.00
Bank Application Menu:
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 3
Enter Account Number: 1001
Enter Withdrawal Amount: 3000
Withdrawal successful. Current balance: $3500.00
Bank Application Menu:
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 4
Enter Account Number: 1001
Account Balance: $3500.00
Bank Application Menu:
63
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Check Balance
5. Exit
Enter your choice: 5
Exiting Bank Application. Thank you!
Inferences:
Creating a simple Bank Application in C++ involves designing classes to represent account holders
and their bank accounts, implementing operations like deposit, withdraw, and balance checking,
and providing a user interface to interact with these functionalities.
Viva Questions:
1. Explain the concept of encapsulation in the context of the Bank Application program
you've implemented. How does the Bank Account class encapsulate data and operations
related to a bank account?
2. Describe the role of exception handling (try, catch, throw) in the Bank Application
program. How does it ensure robustness and reliability when performing operations such
as depositing or withdrawing money?
3. Discuss the advantages of using a menu-driven approach in the Bank Application program
to interact with users. How does this approach enhance user experience and simplify the
implementation of banking operations?
4. Explain the concept of data validation and its importance in the Bank Application program.
How does the program validate user inputs for operations like creating an account or
withdrawing money?
64