[go: up one dir, main page]

0% found this document useful (0 votes)
12 views37 pages

Oopm First 4 Pages

The document outlines the lab assignment for Object Oriented Programming & Methodology (AL305) at Acropolis Institute of Technology and Research, focusing on core OOP concepts in C++/Java. It includes a syllabus, general instructions for lab classes, course objectives and outcomes, and a list of experiments for students to complete. The lab aims to enhance programming skills through practical assignments and projects related to object-oriented programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views37 pages

Oopm First 4 Pages

The document outlines the lab assignment for Object Oriented Programming & Methodology (AL305) at Acropolis Institute of Technology and Research, focusing on core OOP concepts in C++/Java. It includes a syllabus, general instructions for lab classes, course objectives and outcomes, and a list of experiments for students to complete. The lab aims to enhance programming skills through practical assignments and projects related to object-oriented programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

2024-25

Acropolis Institute of
Technology and
Research, Indore Department of CSE
Submitted To: Prof. Sumit Jain
(Artificial Intelligence & Machine
Learning)

Object Oriented Programming &


Methodology (AL305)

Submitted By:
Name of Student
Enrollment No. : 0827
Class/Year/Sem : ALS1/2nd / 3rd

[LAB ASSIGNMENT OOPM (AL-305)]


This lab reinforces understanding of basic object oriented programming concepts (objects,
classes, inheritance, polymorphism, encapsulation, and abstraction.) and their expression in
C++/Java. It also provides practice using non-object aspects of C++/Java.
ACROPOLIS INSTITUTE OF TECHNOLOGY AND
RESEARCH, INDORE

Department of CSE (Artificial Intelligence & Machine Learning)

CERTIFICATE

This is to certify that the experimental work entered in this journal as per the B.

TECH. II year syllabus prescribed by the RGPV was done by Mr./ Ms.

…………………………………B.TECH II year III semester in the Object

Oriented Programming & Methodology Laboratory of this institute during the

academic year 2024- 2025.

Signature of the Faculty


About the Laboratory

The OOPM lab (Object-Oriented Programming Methodology lab) is designed to provide


hands-on experience with core object-oriented programming concepts such as classes,
objects, inheritance, polymorphism, encapsulation, and abstraction. Using languages like
Java or C++, students work on practical exercises to create and manage programs that
demonstrate these principles. The lab emphasizes problem-solving and real-world
applications, often culminating in projects that apply OOP techniques to design systems like
management software or simulations, helping students strengthen their coding skills and
understanding of object-oriented design.

This lab is dedicated for students to work on practical experiments, projects and research
work related to courses such as object oriented programing. This lab purpose is to enhance
the programming skills of the students by giving practical assignments and also requisite
knowledge about Object Oriented Programming through C++ so that they make their own
Applications/Projects using C++.
 GENERAL INSTRUCTIONS FOR LABORATORY CLASSES

 DO’S

 Without Prior permission do not enter into the Laboratory.

 While entering into the LAB students should wear their ID cards.

 The Students should come with proper uniform.

 Students should sign in the LOGIN REGISTER before entering into the
laboratory.

 Students should come with observation and record note book to the laboratory.

 Students should maintain silence inside the laboratory.

 After completing the laboratory exercise, make sure to shutdown the system
properly.

 DONT’S

 Students bringing the bags inside the laboratory.

 Students using the computers in an improper way.

 Students scribbling on the desk and mishandling the chairs.

 Students using mobile phones inside the laboratory.

 Students making noise inside the laboratory.


SYLLABUS
Course: AL305 (Object Oriented Programming & Methodology)
Branch/Year/Sem: Artificial Intelligence & Machine Learning / II / III

Module1: Introduction to Object Oriented Thinking & Object Oriented Programming:


Comparison with Procedural Programming, features of Object oriented paradigm–
Merits and demerits of OO methodology; Object model; Elements of OOPS, IO
processing, Data Type, Type Conversion, Control Statement, Loops, Arrays.

Module2: Encapsulation and Data Abstraction- Concept of Objects: State, Behavior &
Identity of an object; Classes: identifying classes and candidates for Classes Attributes
and Services, Access modifiers, Static members of a Class, Instances, Message passing,
and Construction and destruction of Objects.

Module3: Relationships – Inheritance: purpose and its types, ‘is a’ relationship;


Association, Aggregation. Concept of interfaces and Abstract classes.

Module4: Polymorphism: Introduction, Method Overriding & Overloading, static and


run time Polymorphism. Virtual Function, friend function, Static function, friend class

Module5: Strings, Exceptional handling, Introduction of Multi-threading and Data


collections. Case study like: ATM, Library management system.

HARDWARE AND SOFTWARE REQUIREMENTS:

S. Name of Item Specification


No.
1 Computer System Hard Disk min 5 GB
RAM: 4 GB / 8 GB
Processor: Intel i3 or above

S. Name of Item Specification


No
.
1 Operating system Window XP or above
2 Editor C++ visual studio code, Turbo C++,DevC++
RATIONALE:
The purpose of this subject is to cover the concepts of Object Oriented Programming &
Methodology in terms of Theory and Implementation. The syllabus provides all the
essential concepts of OOP&M.

PREREQUISITE: -

Basic understanding of programming fundamentals, such as variables, data types,


control structures (loops, conditionals), and functions. Familiarity with procedural
programming in languages like C is often expected.

COURSE OBJECTIVES AND OUTCOMES


 Course Objectives
Upon completion of this course, students will be able to do the following:
 Understand object-oriented programming and differentiate between traditional
imperative program and object-oriented program.
 Design and implementation of classes, objects and constructor and also the concept
of structure and static data members etc.
 Understand the role of inheritance and abstract base class in building reusable
code.
 Understand the role of Pointers and virtual function using class and object.
 Gain advanced skills in object oriented programming like stream and file I/O and
to practice the use of object-oriented programming problems.

 Course Outcomes
At the end of the course student will be able to:

 To teach the student to implement object oriented concepts


 Use basic I/O to communicate with the user to populate variables and control
program flow.
 Use arithmetic, logical, relational, and string manipulation expressions to process
data.
 Write a complete class definition with in the class definition, write class and
instance methods including the constructor and overloaded methods.
 Implement appropriate program design using good programming style.
Conceptualize, Analyze and write programs to solve more complicated problems
using the concepts of Object Oriented and java technology.
 Apply validation techniques to build a reliable solution to a given problem.
Apply all the programming concepts as and when required in the future
application development.
Index
Date of Page Date of Grade &
S.No Exp. Name of the Experiment No. Submission Sign of the
Faculty
1 Write a program in C++ which uses functions to swap two
integer & two float numbers by using reference variable
Create a single program to perform following tasks without
2 using library functions:
• To reverse the string accepted as an argument.
• To count the number of characters in string passed as
argument in form of character array.
Create a class Student having data members to store roll
3 number, name of student, name of three subjects, max
marks, min marks, obtained marks. Declared an object of
class student. Provide facilities to input data in data
members and display result of student.
Create a class student having data members to store roll no,
4 name of student, name of 3 subjects, max marks, min
marks, obtain marks. use nesting of member function
Declare an array of object to input data of 3 students.
Provide facilities to display result of all students and to
display result of specific student whose roll number is
given?
Create a class AIML and also create a parameterized
5 constructor AIML(int t) and a copy constructor
AIML(AIML &m) and compute a program to copy data of
one object to another object.
Create a class student. The student class has data members
6 such as roll number, name of student, contact number and
address. create the derived class test which contains data
members representing name of subject, and test marks of 5
subjects. Display all the information of student.
Consider an example of declaring the examination result.
7 Design 3 classes student, exam, result. The student class
has data members such as that representing number, name
of student ,create the class exam, which contains data
members representing name of subject, minimum marks,
maximum marks, obtained marks for 3 subject derive class
result from both student and exam classes.
Create class Polar having data member’s radius and angle.
8 It contains member functions for taking input in data
member function for displaying value of data members.
Class Polar contains declaration of friend function add
which accepts two objects of class Polar and returns objects
of class Polar after addition. Test the class using main
function and object of class Polar.
Create a class Static_demo with static member functions for
9 following tasks: -
• To find factorial by recursive member function
• To check whether a no. is prime or not.
Create a C++ class number with integer data member.
10 Write necessary member function to overload the operator
unary pre and post increment “++”.
Implement polymorphism using inheritance and virtual
11 functions to calculate the area of different shapes (Circle,
Rectangle, and Triangle).
Implement an abstract class Employee that defines a
12
structure for different types of employees and calculates
their salaries using derived classes.
Write a program to implement virtual function using a base
class A & derived class B and also create two member
13 functions show(), display() which will display the name of
class and override them in derived class making show as
virtual function.
Create a class called dimension containing three float data
14 and a constructor to accept values. Also declare a pure
virtual function area () in it. Create three derived classes
Rectangle, Square and Triangle each inheriting dimension
as public. Define corresponding constructors and redefine
virtual function area in each. Write a complete program
and also print the version of virtual function used each time
area is printed.
Write a program to accept the student detail such as name
15 and 3 different marks by get_data() method and display
the name and average of marks using display() method.
Define a friend class for calculating the average of marks
using the method mark_avg().
Program Outcome (PO)

The engineering graduate of this institute will demonstrate:


a) Apply knowledge of mathematics, science, computing and engineering fundamentals to computer
science engineering problems.
b) Able to identify, formulate, and demonstrate with excellent programming, and problem solving skills.
c) Design solutions for engineering problems including design of experiment and processes to meet
desired needs within reasonable constraints of manufacturability, sustainability, ecological,
intellectual and health and safety considerations.
d) Propose and develop effective investigational solution of complex problems using research
methodology; including design of experiment, analysis and interpretation of data, and combination of
information to provide suitable conclusion. synthesis
e) Ability to create, select and use the modern techniques and various tools to solve engineering
problems and to evaluate solutions with an understanding of the limitations.
f) Ability to acquire knowledge of contemporary issues to assess societal, health and safety, legal and
cultural issues.
g) Ability to evaluate the impact of engineering solutions on individual as well as organization in a
societal and environmental context, and recognize sustainable development, and will be aware of
emerging technologies and current professional issues.
h) Capability to possess leadership and managerial skills, and understand and commit to professional
ethics and responsibilities.
i) Ability to demonstrate the team work and function effectively as an individual, with an ability to
design, develop, test and debug the project, and will be able to work with a multi-disciplinary team.
j) Ability to communicate effectively on engineering problems with the community, such as being able
to write effective reports and design documentation.
k) Flexibility to feel the recognition of the need for, and have the ability to engage in independent and
life- long learning by professional development and quality enhancement programs in context of
technological change.
l) A practice of engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and entrepreneurship.
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine
Learning)
Lab: Object Oriented Group / Title:
Programming & Methodology
(AL305)
EVALUATION RECORD Type/ Lab Session:
Name Enrollment No. 0827AL
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1 Title
2 Neatly Drawn and labeled experimental setup
3 Theoretical solution of the instant problem
3.1 Algorithm
3.2 Program
4 Tabulation Sheet
5
INPUT OUTPUT
Results

Page 11
Q1. Write a program in C++ which uses functions to swap two integer & two float numbers by
using reference variable.

#include <iostream>
using namespace std;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

void swap(float &a, float &b) {


float temp = a;
a = b;
b = temp;
}

int main() {
int int1, int2;
float float1, float2;

cout << "Enter two integers: ";


cin >> int1 >> int2;

cout << "Enter two floats: ";


cin >> float1 >> float2;

cout << "\nBefore swapping integers: " << int1 << " " << int2;
swap(int1, int2);
cout << "\nAfter swapping integers: " << int1 << " " << int2;

cout << "\n\nBefore swapping floats: " << float1 << " " << float2;
swap(float1, float2);
cout << "\nAfter swapping floats: " << float1 << " " << float2;

return 0;
}

Page 12
Q2. Create a single program to perform following tasks without using library functions:
• To reverse the string accepted as an argument.
• To count the number of characters in string passed as argument in form of character array.

#include <iostream>
using namespace std;

int countingCharacters(char str[]){


int count = 0;
while (str[count]!= '\0'){
count++;
}
return count;
}

void reverseString(char str[]){


int length = countingCharacters(str);

for (int i = 0; i< length/2; i++){


char temp = str[i];
str[i] = str[length - 1 - i];
str[length - 1 - i] = temp;
}
}

int main(){
char input[100];

cout << "enter a string: "<< endl;


cin >> input;

int charcount = countingCharacters(input);


cout << "number of characters in the string are:" << charcount << endl;

reverseString(input);
cout << "reversed string: " << input << endl;

return 0;
}

Page 13
Q3. Create a class Student having data members to store roll number, name of student, name of three
subjects, max marks, min marks, obtained marks. Declared an object of class student. Provide facilities to
input data in data members and display result of student.

#include <iostream>
using namespace std;

class Student {
private:
int rollNumber;
string name;
string subjects[3];
int maxMarks[3];
int minMarks[3];
int obtainedMarks[3];

public:
void inputDetails(){
cout << "enter roll number: "<< endl;
cin >> rollNumber;

cout << "Enter student name: "<<endl;


getline(cin, name);

for (int i = 0; i < 3; i++) {


cout << "Enter name of subject " << i + 1 << ": ";
getline(cin, subjects[i]);

cout << "Enter maximum marks for " << subjects[i] << ": ";
cin >> maxMarks[i];

cout << "Enter minimum marks required for " << subjects[i] << ": ";
cin >> minMarks[i];

cout << "Enter marks obtained in " << subjects[i] << ": ";
cin >> obtainedMarks[i];

cin.ignore();
}
}

Page 14
void displayResult() {
cout << "\n--- Student Details ---" << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Name: " << name << endl;

int totalMarks = 0;
int totalObtained = 0;
bool passed = true;

cout << "\n--- Subject Details ---" << endl;


for (int i = 0; i < 3; i++) {
cout << "Subject: " << subjects[i] << endl;
cout << "Maximum Marks: " << maxMarks[i] << endl;
cout << "Minimum Marks: " << minMarks[i] << endl;
cout << "Obtained Marks: " << obtainedMarks[i] << endl;

totalMarks += maxMarks[i];
totalObtained += obtainedMarks[i];

if (obtainedMarks[i] < minMarks[i]) {


passed = false;
}
cout << endl;
}

cout << "Total Marks: " << totalMarks << endl;


cout << "Total Obtained: " << totalObtained << endl;
cout << "Result: " << (passed ? "Pass" : "Fail") << endl;
}
};

int main() {
Student student;

student.inputDetails();
student.displayResult();

return 0;
}

Page 15
Q4. Create a class student having data members to store roll no, name of student, name of 3 subjects, max
marks, min marks, obtain marks. use nesting of member function Declare an array of object to input data
of 3 students. Provide facilities to display result of all students and to display result of specific student
whose roll number is given?

#include <iostream>
using namespace std;

class Student {
private:
int rollNo;
char name[50];
char subjects[3][50];
int maxMarks[3];
int minMarks[3];
int obtainedMarks[3];

public:

void inputData() {
cout << "Enter Roll Number: ";
cin >> rollNo;

cout << "Enter Name: ";


cin >> name;

for (int i = 0; i < 3; i++) {


cout << "Enter Subject " << i + 1 << " Name: ";
cin >> subjects[i];

cout << "Enter Maximum Marks for " << subjects[i] << ": ";
cin >> maxMarks[i];

cout << "Enter Minimum Marks for " << subjects[i] << ": ";
cin >> minMarks[i];

cout << "Enter Obtained Marks for " << subjects[i] << ": ";

Page 16
cin >> obtainedMarks[i];
}
}

void displayResult() const {


cout << "\nRoll Number: " << rollNo
<< "\nName: " << name;
for (int i = 0; i < 3; i++) {
cout << "\nSubject: " << subjects[i]
<< " Max: " << maxMarks[i]
<< " Min: " << minMarks[i]
<< " Obtained: " << obtainedMarks[i];
}
cout << "\n";
}

int getRollNo() const {


return rollNo;
}
};

int main() {
const int numStudents = 3;
Student students[numStudents];

for (int i = 0; i < numStudents; i++) {


cout << "\nEnter details for Student " << i + 1 << ":\n";
students[i].inputData();
}

cout << "\nDisplaying results of all students:";


for (int i = 0; i < numStudents; i++) {
students[i].displayResult();
}

int searchRollNo;
cout << "\nEnter Roll Number to search: ";
cin >> searchRollNo;

bool found = false;


for (int i = 0; i < numStudents; i++) {
if (students[i].getRollNo() == searchRollNo) {
cout << "\nDisplaying result for Roll Number " << searchRollNo << ":\n";
students[i].displayResult();

Page 17
found = true;
break;
}
}

if (!found) {
cout << "\nStudent with Roll Number " << searchRollNo << " not found.\n";
}

return 0;
}

Page 18
Q5: Create a class AIML and also create a parameterized constructor AIML(int t) and a copy constructor
AIML(AIML &m) and compute a program to copy data of one object to another object.

#include <iostream>
using namespace std;

class AIML{
private:
int data;

public:
AIML(int d){
data = d;
cout <<"parameterized constructor called. data :"<< data << endl;

}
AIML(const AIML &m){
data = m.data;
cout <<"Copy constructor called. Copied Data: " << data << endl;
}
void display() const{
cout << "data: "<<data << endl;
}
};
int main(){
AIML std1(44);
AIML std2 = std1;
cout << "\nStudent 1 :";
std1.display();
cout<< "\nStudent 2 :";
std2.display();

return 0;
}

Page 19
Q6: Create a class student. The student class has data members such as roll number, name of student,
contact number and address. create the derived class test which contains data members representing name
of subject, and test marks of 5 subjects. Display all the information of student.

#include <iostream>
#include <string>
using namespace std;

class Student {
protected:
int rollNumber;
string name;
string contactNumber;
string address;

public:

Student(int r, string n, string c, string a) {


rollNumber = r;
name = n;
contactNumber = c;
address = a;
}

void displayStudentInfo() {
cout << "Roll Number: " << rollNumber << endl;
cout << "Name: " << name << endl;
cout << "Contact Number: " << contactNumber << endl;
cout << "Address: " << address << endl;
}
};

class Test : public Student {


private:
string subjects[5];

Page 20
int marks[5];

public:

Test(int r, string n, string c, string a, string sub[], int m[])


: Student(r, n, c, a) {
for (int i = 0; i < 5; i++) {
subjects[i] = sub[i];
marks[i] = m[i];
}
}

void displayInfo() {
displayStudentInfo();
cout << "Subjects and Marks:" << endl;
for (int i = 0; i < 5; i++) {
cout << subjects[i] << ": " << marks[i] << endl;
}
}
};

int main() {
string subjects[] = {"Math", "Physics", "Chemistry", "English", "Computer"};
int marks[] = {85, 90, 78, 88, 95};

Test student1(1, "sanyak", "898959989", "1554 padmaviati", subjects, marks);

student1.displayInfo();

return 0;
}

Page 21
Q7: Consider an example of declaring the examination result. Design 3 classes student, exam, result. The
student class has data members such as that representing number, name of student ,create the class exam,
which contains data members representing name of subject, minimum marks, maximum marks, obtained
marks for 3 subject derive class result from both student and exam classes.

#include <iostream>
using namespace std;

class Student {
protected:
int studentNumber;
char name[50];

public:

void setStudentDetails(int number, const char* studentName) {


studentNumber = number;

int i = 0;
while (studentName[i] != '\0' && i < 49) {
name[i] = studentName[i];
i++;
}
name[i] = '\0';
}

void displayStudentInfo() {
cout << "Student Number: " << studentNumber << endl;
cout << "Name: " << name << endl;
}
};

Page 22
class Exam {
protected:
char subjects[3][20];
int maxMarks[3];
int obtainedMarks[3];

public:

void setExamDetails(const char subNames[3][20], const int max[], const int obtained[]) {
for (int i = 0; i < 3; i++) {

int j = 0;
while (subNames[i][j] != '\0' && j < 19) {
subjects[i][j] = subNames[i][j];
j++;
}
subjects[i][j] = '\0';

maxMarks[i] = max[i];
obtainedMarks[i] = obtained[i];
}
}

void displayExamDetails() {
for (int i = 0; i < 3; i++) {
cout << "Subject: " << subjects[i]
<< ", Max Marks: " << maxMarks[i]
<< ", Obtained Marks: " << obtainedMarks[i] << endl;
}
}
};

class Result : public Student, public Exam {


public:
void displayResult() {
int totalMarks = 0, totalObtained = 0;

for (int i = 0; i < 3; i++) {


totalMarks += maxMarks[i];
totalObtained += obtainedMarks[i];
}

cout << "\n--- Result ---\n";


displayStudentInfo();
displayExamDetails();
cout << "Total Marks: " << totalMarks << endl;
cout << "Marks Obtained: " << totalObtained << endl;

Page 23
cout << "Percentage: " << (totalObtained * 100.0 / totalMarks) << "%\n";
}
};

int main() {
Result result;

result.setStudentDetails(11, "Aditya");

const char subjects[3][20] = {"Maths", "Python", "dsa"};


const int maxMarks[3] = {100, 100, 100};
const int obtainedMarks[3] = {90, 85, 80};

result.setExamDetails(subjects, maxMarks, obtainedMarks);

result.displayResult();

return 0;
}

Q8: Create class Polar having data member’s radius and angle. It contains member functions for taking
input in data member function for displaying value of data members. Class Polar contains declaration of
friend function add which accepts two objects of class Polar and returns objects of class Polar after
addition. Test the class using main function and object of class Polar.

#include <iostream>
#include <cmath>
using namespace std;

class Polar {
private:
double radius;
double angle;

public:

Polar() : radius(0), angle(0) {}

Page 24
Polar(double r, double a) : radius(r), angle(a) {}

void input() {
cout << "Enter radius: ";
cin >> radius;
cout << "Enter angle (in degrees): ";
double angleDegrees;
cin >> angleDegrees;
angle = angleDegrees * M_PI / 180.0;
}

void display() const {


cout << "Radius: " << radius << ", Angle: " << angle * 180.0 / M_PI << " degrees" << endl;
}

friend Polar add(const Polar& p1, const Polar& p2);


};

Polar add(const Polar& p1, const Polar& p2) {

double x1 = p1.radius * cos(p1.angle);


double y1 = p1.radius * sin(p1.angle);

double x2 = p2.radius * cos(p2.angle);


double y2 = p2.radius * sin(p2.angle);

double x = x1 + x2;
double y = y1 + y2;

double newRadius = sqrt(x * x + y * y);


double newAngle = atan2(y, x);

return Polar(newRadius, newAngle);


}

int main() {
Polar p1, p2;

cout << "Enter details for the first polar coordinate:" << endl;
p1.input();

cout << "Enter details for the second polar coordinate:" << endl;
p2.input();

Polar result = add(p1, p2);

cout << "\nFirst Polar Coordinate:" << endl;


p1.display();

Page 25
cout << "\nSecond Polar Coordinate:" << endl;
p2.display();

cout << "\nResultant Polar Coordinate after Addition:" << endl;


result.display();

return 0;
}

Q9: Create a class Static_demo with static member functions for following tasks: -
• To find factorial by recursive member function
• To check whether a no. is prime or not.

#include <iostream>
using namespace std;

class Static_demo {
public:

static int factorial(int n) {


if (n <= 1) {
return 1;

Page 26
}
return n * factorial(n - 1);
}

static bool isPrime(int n) {


if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
};

int main() {
int num;

cout << "Enter a number to calculate factorial: ";


cin >> num;
cout << "Factorial of " << num << " is " << Static_demo::factorial(num) << endl;

cout << "Enter a number to check if it is prime: ";


cin >> num;
if (Static_demo::isPrime(num)) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}

return 0;
}

Q10: Create a C++ class number with integer data member. Write necessary member function to overload the
operator unary pre and post increment “++”.

#include <iostream>
using namespace std;

class Number {
private:
int value;

public:

Page 27
Number(int v = 0) : value(v) {}

void display() const {


cout << "Value: " << value << endl;
}

Number& operator++() {
++value;
return *this;
}

Number operator++(int) {
Number temp = *this;
value++;
return temp;
}
};

int main() {
Number num(5);

cout << "Initial Value:" << endl;


num.display();

cout << "\nUsing Pre-Increment (++num):" << endl;


++num;
num.display();

cout << "\nUsing Post-Increment (num++):" << endl;


num++;
num.display();

return 0;
}

Q11: Implement polymorphism using inheritance and virtual functions to calculate the area of different shapes
(Circle, Rectangle, and Triangle).

#include <iostream>
#include <cmath>
using namespace std;

class Shape {
public:

Page 28
virtual void calculateArea() const {
cout << "This is a generic shape. Area calculation not implemented." << endl;
}

virtual ~Shape() {}
};

class Circle : public Shape {


private:
double radius;

public:

Circle(double r) : radius(r) {}

void calculateArea() const override {


double area = M_PI * radius * radius;
cout << "Area of Circle: " << area << endl;
}
};

class Rectangle : public Shape {


private:
double length, width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

void calculateArea() const override {


double area = length * width;
cout << "Area of Rectangle: " << area << endl;
}
};

class Triangle : public Shape {


private:
double base, height;

public:

Triangle(double b, double h) : base(b), height(h) {}

void calculateArea() const override {


double area = 0.5 * base * height;
cout << "Area of Triangle: " << area << endl;
}

Page 29
};

int main() {

Shape* circle = new Circle(5.0);


Shape* rectangle = new Rectangle(4.0, 6.0);
Shape* triangle = new Triangle(4.0, 5.0);

cout << "Calculating areas using polymorphism:" << endl;

circle->calculateArea();
rectangle->calculateArea();
triangle->calculateArea();
}

Q12: Implement an abstract class Employee that defines a structure for different types of employees and
calculates their salaries using derived classes.

#include <iostream>
using namespace std;

Page 30
class Employee {
protected:
int id_number;

public:
Employee(int id) : id_number(id) {}

virtual double calculateSalary() const = 0;

void getDetails() const {


cout << "Employee ID: " << id_number << endl;
}

virtual ~Employee() {}
};

class SalariedEmployee : public Employee {


private:
double monthlySalary;

public:
SalariedEmployee(int id, double salary) : Employee(id), monthlySalary(salary) {}

double calculateSalary() const override {


return monthlySalary;
}
};

class HourlyEmployee : public Employee {


private:
double hourlyRate;
double hoursWorked;

public:
HourlyEmployee(int id, double rate, double hours)
: Employee(id), hourlyRate(rate), hoursWorked(hours) {}

double calculateSalary() const override {


return hourlyRate * hoursWorked;
}
};

class CommissionEmployee : public Employee {


private:
double sales;
double commissionRate;

Page 31
public:
CommissionEmployee(int id, double salesAmount, double rate)
: Employee(id), sales(salesAmount), commissionRate(rate) {}

double calculateSalary() const override {


return sales * commissionRate;
}
};

int main() {
SalariedEmployee salaried(1, 5000);
HourlyEmployee hourly(2, 20, 160);
CommissionEmployee commission(3, 10000, 0.1);

salaried.getDetails();
cout << "Salary: $" << salaried.calculateSalary() << endl;

hourly.getDetails();
cout << "Salary: $" << hourly.calculateSalary() << endl;

commission.getDetails();
cout << "Salary: $" << commission.calculateSalary() << endl;

return 0;
}

Page 32
Q13: Write a program to implement virtual function using a base class A & derived class B and also create
two member functions show(), display() which will display the name of class and override them in
derived class making show as virtual function.
#include <iostream>
using namespace std;

class A {
public:

virtual void show() const {


cout << "This is class A (Base class): show()" << endl;
}

void display() const {


cout << "This is class A (Base class): display()" << endl;
}

virtual ~A() {}
};

class B : public A {
public:

void show() const override {


cout << "This is class B (Derived class): show()" << endl;
}

void display() const {


cout << "This is class B (Derived class): display()" << endl;
}
};

Page 33
int main() {
A* basePtr;
B derivedObj;

basePtr = &derivedObj;

cout << "Calling functions through base class pointer:" << endl;
basePtr->show();
basePtr->display();

cout << "\nCalling functions directly through derived class object:" << endl;
derivedObj.show();
derivedObj.display();

return 0;
}

Q14: Create a class called dimension containing three float data and a constructor to accept values. Also
declare a pure virtual function area () in it. Create three derived classes Rectangle, Square and Triangle
each inheriting dimension as public. Define corresponding constructors and redefine virtual function
area in each. Write a complete program and also print the version of virtual function used each time
area is printed.

#include <iostream>
#include <string>
using namespace std;

class Dimension {
protected:
float a, b, c;

public:

Dimension(float x, float y, float z = 0) : a(x), b(y), c(z) {}

virtual float area() = 0;

virtual ~Dimension() {}

virtual void version() const {


cout << "This is the base class Dimension's virtual function." << endl;
}
};

class Rectangle : public Dimension {

Page 34
public:

Rectangle(float length, float breadth) : Dimension(length, breadth) {}

float area() override {


version();
return a * b;
}

void version() const override {


cout << "This is the Rectangle class's virtual function for area." << endl;
}
};

class Square : public Dimension {


public:

Square(float side) : Dimension(side, side) {}

float area() override {


version();
return a * a;
}

void version() const override {


cout << "This is the Square class's virtual function for area." << endl;
}
};

class Triangle : public Dimension {


public:

Triangle(float base, float height) : Dimension(base, height) {}

float area() override {


version();
return 0.5 * a * b;
}

void version() const override {


cout << "This is the Triangle class's virtual function for area." << endl;
}
};

int main() {

Dimension* rectangle = new Rectangle(10.0f, 5.0f);


Dimension* square = new Square(4.0f);

Page 35
Dimension* triangle = new Triangle(6.0f, 8.0f);

cout << "Rectangle area: " << rectangle->area() << endl;


cout << "Square area: " << square->area() << endl;
cout << "Triangle area: " << triangle->area() << endl;

delete rectangle;
delete square;
delete triangle;

return 0;
}

Q15: Write a program to accept the student detail such as name and 3 different marks by get_data()
method and display the name and average of marks using display() method. Define a friend class for
calculating the average of marks using the method mark_avg().

#include <iostream>
#include <string>
using namespace std;

class MarkAvg;

class Student {
private:
string name;
float marks[3];

public:

void get_data() {
cout << "Enter student name: ";
cin >> name;
cout << "Enter 3 marks: ";
for (int i = 0; i < 3; i++) {
cin >> marks[i];
}

Page 36
}

void display() {
cout << "Student Name: " << name << endl;
MarkAvg m;
cout << "Average Marks: " << m.mark_avg(*this) << endl;
}

friend class MarkAvg;


};

class MarkAvg {
public:

float mark_avg(Student& student) {


float total = 0;
for (int i = 0; i < 3; i++) {
total += student.marks[i];
}
return total / 3;
}
};

int main() {
Student student;
student.get_data();
student.display();

return 0;
}

Page 37

You might also like