All Assi.......
All Assi.......
//#include <stdio.h>
//#include <string> // Note: This is included, but not used in this example
//
//struct Student {
// int roll_number;
// char name[20];
// float cgpa;
//};
//
//// Function to get data for a Student object
//void getdata(Student &s) { // Use reference instead of pointer
// printf("Enter Name: ");
// scanf("%19s", s.name); // Limit input to avoid overflow
//
// printf("Enter Roll Number: ");
// scanf("%d", &s.roll_number);
//
// printf("Enter CGPA: ");
// scanf("%f", &s.cgpa);
//}
//
//// Function to print data for a Student object
//void printdata(const Student &s) { // Use const reference for efficiency
// printf("Name: %s\n", s.name);
// printf("Roll Number: %d\n", s.roll_number);
// printf("CGPA: %.2f\n", s.cgpa);
//}
//
//int main() {
// Student student; // Define a Student object
//
// getdata(student); // Pass by reference
// printdata(student); // Pass by const reference
//
// return 0;
//}
//Q2. Modify the above code to accept the print and data of 10 student using array
of structure
#include <stdio.h>
struct Student {
int roll_number;
char name[20];
float cgpa;
};
int main() {
Student students[10]; // Define an array of Student objects
int i;
return 0;
}
//ASSIGNMENT 2
#include <iostream>
#include <string>
// Prompt the user to enter the name and store it in the name variable
cout << "Enter Name: ";
cin >> s.name;
// Prompt the user to enter the CGPA and store it in the cgpa variable
cout << "Enter CGPA: ";
cin >> s.cgpa;
}
int main() {
// Declare three Student variables (s1, s2, and s3) to store the details of
three different students
Student s1, s2, s3;
//ASSIGNMENT 3
/* Q1- write a program in C++ to create a class employee, take three data memebers
Name,Employee_id,Salary.
Input the data and display the detail using two separate functions .
Use the concept of encapsulation .Also in the same program display the size of
objects that are created. */
#include <iostream>
#include <string>
public:
// Function to input employee details from the user
void inputData() {
// Asking for the employee's name
cout << "Enter Name: ";
// Clearing the input buffer to prevent any issues with reading the name
cin.ignore();
/* Q2- Write a program in c++ to calculate the simple intrest.Hide the data and the
function used to calculate the intrest .
Invoke the private function using a public function to get the result .*/
#include <iostream>
// Private function to calculate the interest using the simple interest formula
void calculateInterest() {
interest = (principal * rate * time) / 100;
}
public:
// Public function to set the values for principal, rate, and time
// It also calls the calculateInterest function to compute the interest
void setValues(double p, double r, double t) {
principal = p; // Set the principal amount
rate = r; // Set the interest rate
time = t; // Set the time period
calculateInterest(); // Calculate the interest based on the input values
}
// Public function to return the calculated interest
double getInterest() {
return interest; // Return the value of the interest that was calculated
}
};
int main() {
// Create an object of the 'InterestCalculator' class
InterestCalculator calculator;
// Call the setValues function of the 'calculator' object to set the inputs
// and calculate the interest based on the inputs
calculator.setValues(principal, rate, time);
/* Q3- Write a program to create a class time, accept hour,min,sec through data
members.
Accept two diffrent instances of time and calculate the diffrence of time .*/
#include <iostream>
#include <iomanip> // For setting output format
using namespace std;
// Define a class to represent Time
class Time {
public:
// Public member variables for hour, minute, and second
int hour;
int minute;
int second;
// Function to calculate and display the difference between two Time objects
void calculateDifference(const Time& t1, const Time& t2) {
// Validate both time objects to ensure they contain valid time values
if (!isTimeValid(t1) || !isTimeValid(t2)) {
cout << "Invalid time input. Please try again." << endl;
return; // Exit the function if time is invalid
}
// Ensure that the second time is not larger than the first time
if (t1.hour < t2.hour ||
(t1.hour == t2.hour && t1.minute < t2.minute) ||
(t1.hour == t2.hour && t1.minute == t2.minute && t1.second < t2.second)) {
cout << "Error: The second time cannot be later than the first time." <<
endl;
return; // Exit the function if the second time is later
}
int main() {
Time time1, time2; // Create two Time objects to store user input
char choice; // Variable to store the user's choice for continuing or exiting
do {
// Prompt the user to enter the first time
cout << "Enter first time:" << endl;
time1.inputTime(); // Call inputTime() to get user input for time1
//ASSIGNMENT 4
#include <iostream> // Include input-output stream library to use cin and cout
using namespace std; // Use the standard namespace to avoid prefixing std:: before
standard functions
int main() {
TriangularNumber tn; // Create an object of the TriangularNumber class
int num; // Declare a variable to store user input
/* Q2- Write a program in c++ to create a class student , take data members as
student name,ge,roll_no,branch and display the data through member functions.
Make university code a static member variable and acess it through static
functions.*/
using namespace std; // We are using the standard namespace to avoid prefixing
'std::' to standard library names
public:
// Static member variable to store a university code that is shared among all
instances of the class
static string universityCode;
// Clear the input buffer again before reading another string (getline)
cin.ignore();
// Initialize the static member variable "universityCode" with the value "XYZ123"
string Student::universityCode = "XYZ123";
int main() {
// Create an object of the class "Student"
Student s1;
// Access the static member function using the class name to get the university
code
cout << "\nUniversity Code: " << Student::getUniversityCode() << endl;
return 0;
}
/
***********************************************************************************
**********************
***********************************************************************************
***********************/
/* Q3- Extend the question 2 to accept and print the details of 5 students*/
#include <iostream>
#include <string>
public:
static string universityCode; // Static member variable to store university
code (common for all students)
int main() {
const int numStudents = 5; // Define a constant for the number of students
Student students[numStudents]; // Create an array of 5 Student objects
// Display the university code (static variable shared among all students)
cout << "\nUniversity Code: " << Student::getUniversityCode() << endl;
//ASSIGNMENT 5
#include <iostream>
using namespace std;
public:
// Function to input the length and breadth of the rectangle
void input() {
cin >> length >> breadth; // Taking input from the user
}
public:
// Function to input the height and base of the triangle
void input() {
cin >> height >> base; // Taking input from the user
}
public:
// Function to input the radius of the circle
void input() {
cin >> radius; // Taking input from the user
}
int main() {
// Working with the Rectangle
Rectangle r1;
cout << "Enter dimensions for Rectangle:" << endl;
r1.input(); // Input the length and breadth of the rectangle
r1.show(); // Display the dimensions of the rectangle
double ar = calrec(r1); // Calculate the area using the friend function
cout << "Area of Rectangle: " << ar << endl; // Display the area
return 0;
}
/* Q2- write a friend function in c++ to add 2 objects of the same class
and display the sum of the two values which contains one integer value and one
floating point value.*/
int main() {
// Create two objects of the class "Number" with initial values
Number num1(5, 2.5); // num1 is created with integer 5 and float 2.5
Number num2(3, 1.7); // num2 is created with integer 3 and float 1.7
// Call the friend function "add" to add the values of num1 and num2
add(num1, num2);
#include <iostream>
public:
// Member function to accept a value and store it in the 'value' variable
void acceptValue(int val) {
value = val; // Assign the passed value to the object's 'value' variable
}
// Assign the temporary value (which is obj1's original value) to obj2's value
obj2.value = temp;
}
// Call the friend function to exchange the values between obj1 and obj2
exchangeValues(obj1, obj2);
#include <iostream>
class ClassA {
private:
int arrA[5]; // Private array to hold elements of Class A
public:
// Function to accept input for array A
void acceptArrayA() {
cout << "Enter 5 elements for array A: " << endl;
for (int i = 0; i < 5; i++) {
cout << "Element " << i + 1 << ": ";
cin >> arrA[i];
}
}
class ClassB {
private:
int arrB[5]; // Private array to hold elements of Class B
public:
// Function to accept input for array B
void acceptArrayB() {
cout << "Enter 5 elements for array B: " << endl;
for (int i = 0; i < 5; i++) {
cout << "Element " << i + 1 << ": ";
cin >> arrB[i];
}
}
class ClassC {
private:
int arrC[5]; // Private array to hold elements of Class C (the sum)
public:
// Function to display the elements of array C
void displayArrayC() {
cout << "Array C (sum of A and B): ";
for (int i = 0; i < 5; i++) {
cout << arrC[i] << " "; // Display each element of the result array
}
cout << endl;
}
// Friend function to add elements of arrays from Class A and Class B, and store
the result in Class C
void addArrays(ClassA &objA, ClassB &objB, ClassC &objC) {
for (int i = 0; i < 5; i++) {
objC.arrC[i] = objA.arrA[i] + objB.arrB[i]; // Add corresponding elements
of arrays A and B
}
}
int main() {
// Create objects of ClassA, ClassB, and ClassC
ClassA objA;
ClassB objB;
ClassC objC;
return 0;
}
//ASSIGNMENT 6
/*Q1. Write a menu driven program in C++ to add or subtract integer values or
floatingpoint numbers.
Create a class named Add_Sub and overload member functions for doing the operations
on integer and float.
Accept first choice from the user to select add or subtract operation and
second choice to select integer or floating point numbers.
Use read only functions with 'const' keyword to display the result*/
using namespace std; // Use the standard namespace to avoid writing "std::" before
each input/output operation
public:
// Function to add two integer numbers and store the result in 'result'
void addInt(int a, int b) {
result = a + b;
}
// Function to subtract two integer numbers and store the result in 'result'
void subInt(int a, int b) {
result = a - b;
}
// Function to add two floating-point numbers and store the result in 'fresult'
void addFloat(float a, float b) {
fresult = a + b;
}
int main() {
Add_Sub obj; // Create an object 'obj' of the Add_Sub class
int choice1, choice2; // Variables to store user's choices for operations and
data type
int num1, num2; // Variables to store integer values entered by the user
float fnum1, fnum2; // Variables to store floating-point values entered by the
user
// Display menu for the user to select the operation: Add or Subtract
cout << "Menu:\n";
cout << "1. Add\n";
cout << "2. Subtract\n";
cout << "Enter your choice: ";
cin >> choice1; // Store the user's choice in 'choice1'
// Based on the user's choice for data type, perform the corresponding
operations
if (choice2 == 1) { // If the user selects 'Integer'
cout << "Enter two integer values: ";
cin >> num1 >> num2; // Input two integer values
} else {
// If the user enters an invalid choice for data type
cout << "Invalid choice!\n";
}
return 0; // Return 0 to indicate successful execution of the program
}
#include <iostream>
class Calculator {
private:
int num1, num2, result;
float fnum1, fnum2, fresult;
public:
void addInt(int a, int b) {
result = a + b;
}
int main() {
Calculator obj;
char choice, op;
int num1, num2;
float fnum1, fnum2;
do {
cout << "Menu:\n";
cout << "1. Add\n";
cout << "2. Subtract\n";
cout << "3. Multiply\n";
cout << "4. Divide\n";
cout << "5. Modulus (integer only)\n";
cout << "Enter your choice: ";
cin >> choice;
if (op == '1') {
cout << "Enter two integer values: ";
cin >> num1 >> num2;
switch (choice) {
case '1':
obj.addInt(num1, num2);
break;
case '2':
obj.subInt(num1, num2);
break;
case '3':
obj.mulInt(num1, num2);
break;
case '4':
obj.divInt(num1, num2);
break;
case '5':
obj.modInt(num1, num2);
break;
default:
cout << "Invalid choice!\n";
}
obj.displayIntResult();
} else if (op == '2') {
cout << "Enter two floating-point values: ";
cin >> fnum1 >> fnum2;
switch (choice) {
case '1':
obj.addFloat(fnum1, fnum2);
break;
case '2':
obj.subFloat(fnum1, fnum2);
break;
case '3':
obj.mulFloat(fnum1, fnum2);
break;
case '4':
obj.divFloat(fnum1, fnum2);
break;
default:
cout << "Invalid choice!\n";
}
obj.displayFloatResult();
} else {
cout << "Invalid choice!\n";
}
cout << "Enter 'x' to exit, any other key to continue: ";
cin >> choice;
} while (choice != 'x');
return 0;
}
//ASSIGNMENT 7
(Constructor overloading)
/*
Q1.Write a program to input two numbers through parameterized constructor and
display.*/
#include<iostream>
using namespace std;
// Public members of the class (these can be accessed outside the class)
public:
// Constructor: A special function that gets called automatically when an
object of this class is created
// This is a parameterized constructor, meaning it takes two arguments (int
a, int b)
NumberPair(int a, int b) : num1(a), num2(b)
{
// This syntax in the constructor is called the initialization list
// It assigns the values of 'a' and 'b' to the member variables 'num1'
and 'num2' respectively
}
int main() // The main function, where the program starts executing
{
int a, b; // Declare two integer variables 'a' and 'b'
// Create an object of the 'NumberPair' class, passing 'a' and 'b' to the
constructor
// This automatically calls the constructor and assigns the values of 'a' and
'b' to 'num1' and 'num2'
NumberPair pair(a, b);
// Call the 'display' function to print the values of 'num1' and 'num2'
pair.display();
#include <iostream>
using namespace std;
class Rectangle
{
int width, height;
public:
Rectangle() : width(0), height(0) {}
Rectangle(int w, int h = 10) : width(w), height(h) {}
int main()
{
Rectangle rect1,rect2(5),rect3(5,20);
cout << "Area of rect1:" << rect1.area() << endl;
cout << "Area of rect2:" << rect2.area() << endl;
cout << "Area of rect3:" << rect3.area() << endl;
return 0;
}
/*Q3. Define a rectangle class. Data members - Length and breadth as double type.
Include the following member function:
a)Constructor: Assigns default values (5 to length and 3 to breadth)
b)Display data members through a read only function
c)Calculate area
d)Calculate circumference
e)Read data members*/
#include <iostream>
using namespace std;
class Rectangle {
// Private data members to store the dimensions of the rectangle
double length, breadth;
public:
// Constructor: Initializes length to 5 and breadth to 3 by default
Rectangle() : length(5), breadth(3) {}
int main() {
// Create an object 'rect' of class Rectangle, initialized with default values
Rectangle rect;
// Calculate and display the area and circumference using default values
cout << "Area: " << rect.area() << endl;
cout << "Circumference: " << rect.circumference() << endl;
return 0;
}
//Q4.Write a program to add two complex number. Show the use of constructor
overloading.
#include<iostream>
using namespace std;
class complex {
// These are private data members that store the real and imaginary parts of a
complex number
int real;
int imag;
public:
// Function to display the complex number
void show() {
// Print the real part first
cout << real;
// Add the real parts and assign the result to the real part of 't'
t.real = real + c.real;
// Add the imaginary parts and assign the result to the imaginary part
of 't'
t.imag = imag + c.imag;
int main() {
// Create two complex numbers using the constructor
// c1 is initialized to 2 + (-5)i and c2 is initialized to -3 + 4i
complex c1(2, -5);
complex c2(-3, 4);
// Create a third complex number (c3) that will hold the sum of c1 and c2
complex c3;
// Assignment – 8
(Constructor)
/*Define a class stack that has member variables- an array of integers, size of the
array, stack top.
Implement the functionality of a stack using the follow member functions:
1. Constructor (initializes all array elements to zero)
2. Display the stack
3. Pop
4. Push*/
#include<iostream>
using namespace std;
public:
// Constructor to initialize the stack
Stack(int s) {
size = s; // Set the size of the stack
arr = new int[size]; // Allocate memory for the stack array
top = -1; // Initialize top to -1 (indicating the stack is
empty)
// Initialize all array elements to zero
for(int i = 0; i < size; i++) {
arr[i] = 0;
}
}
int main() {
int y, ch, num;
switch (ch) {
case 1:
// Push operation
cout << "Enter number to push into Stack" << endl;
cin >> num;
s.push(num);
break;
case 2:
// Pop operation
s.pop();
break;
case 3:
// Display the current stack
s.display();
break;
case 4:
// Exit the program
exit(0);
}
}
return 0;
}
int main() {
// Declaring and initializing two string variables
string str1 = "Hello "; // First string with the value "Hello "
string str2 = "Hiii"; // Second string with the value "Hiii"
/*Q3. Write a program in c++ to create a class time(hour, minute and second) and
initialize the time through constructor. Define a
function to show the time in HH:MM:SS format. Define another function to welcome
the user by showing the
message Good Morning/Afternoon/Evening as per the time initialized through
constructor. Destroy the object
through destructor.*/
#include <iostream>
#include <iomanip> // Required for setting output formatting (setw, setfill)
using namespace std;
class Time {
private:
int hour, minute, second; // Member variables to store hours, minutes, and
seconds
public:
// Constructor to initialize the time
Time(int h, int m, int s) : hour(h), minute(m), second(s) {
// The constructor initializes the time with given values of hour, minute,
and second
}
int main() {
// Creating an instance of Time with hour 14 (2 PM), minute 30, and second 45
Time t(14, 30, 45); // This automatically calls the constructor
// After main function ends, the object 't' will be destroyed automatically
// This will call the destructor and print "Time object destroyed."
return 0;
}
/*Q4. Write a program in c++ to create a class Player having data members Player
ID, Player name and Game specification.
Copy one object of Player class to another object using copy constructor.*/
#include <iostream>
#include <cstring> // for strcpy and strlen
class Player {
private:
int playerID; // Data member to store the player's ID
char playerName[50]; // Data member to store the player's name (character
array)
char gameSpec[50]; // Data member to store the player's game
specification (character array)
public:
// Parameterized Constructor
Player(int id, const char* name, const char* game) : playerID(id) {
// Initialize playerID with the value passed in the constructor
// Copy the player's name and game specification using strcpy
strcpy(playerName, name); // Copies the string 'name' to 'playerName'
strcpy(gameSpec, game); // Copies the string 'game' to 'gameSpec'
}
int main() {
// Create an object 'p1' of class Player using the parameterized constructor
Player p1(1, "Madhav", "Soccer");
// Create another object 'p2' by copying 'p1' using the copy constructor
// This triggers the copy constructor and copies the data from p1 to p2
Player p2 = p1;
// Display the data of the first player
p1.display();
return 0;
}
// Assignment – 9
// (Operator
Overloading)
/*Q1. Write a simple program to overload the increment operator. The increment
operator should increase the values of all the integer and floating-point data
members by 1.
For character data members the increment operator should update the value to the
next character.*/
#include <iostream>
using namespace std;
class MyClass {
private:
int intval;
float floatval;
char charval;
public:
// Constructor to initialize the values of the object
MyClass(int i, float f, char c) : intval(i), floatval(f), charval(c) {}
int main() {
MyClass obj(10, 20.5, 'A'); // Creating an object with initial values
obj.display(); // Display initial values
++obj; // Using overloaded increment operator
obj.display(); // Display values after increment
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class MyString {
private:
string str;
public:
// Constructor to initialize the string
MyString(string s) : str(s) {}
int main() {
MyString str1("Hello ");
MyString str2("World");
return 0;
}
/*Q3. Write a program to overload the binary + operator to perform addition of two
objects. The
operator function should add the integer and float values of the two objects and
store it in the
third object.*/
#include <iostream>
using namespace std;
class MyClass {
private:
int intval; // Integer data member
float floatval; // Float data member
public:
// Constructor to initialize integer and float values
MyClass(int i, float f) : intval(i), floatval(f) {}
int main() {
// Create two MyClass objects with initial values
MyClass obj1(10, 20.5);
MyClass obj2(30, 40.5);
// Use the overloaded + operator to add obj1 and obj2, storing the result in a
new object
MyClass result = obj1 + obj2;
return 0;
}
/*Q4. Write the program in Q3 to implement the operator overloading using friend
function.*/
#include <iostream>
using namespace std;
class MyClass {
private:
int intval; // Integer data member
float floatval; // Float data member
public:
// Constructor to initialize integer and float values
MyClass(int i, float f) : intval(i), floatval(f) {}
int main() {
// Create two MyClass objects with initial values
MyClass obj1(10, 20.5);
MyClass obj2(30, 40.5);
// Use the overloaded + operator to add obj1 and obj2, storing the result in a
new object
MyClass result = obj1 + obj2;
return 0;
}
ASSIGNMENT:-10
#include<iostream>
#include<string>
using namespace std;
//base class
class Person
{
protected:
string name;
int id;
public:
//constructor
Person(string n,int i)
{
name = n;
id = i;
}
Person()
{
}
void AcceptPersonDetails()
{
cout << "Enter name: ";
getline(cin, name);
cout << "Enter ID: ";
cin >> id;
cin.ignore();
}
void DisplayPersonDetails()
{
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
}
};
//salary class
class Salary : public Person
{
private:
string designation;
double basic;
double TA,DA,HRA,PF,GrossSalary,NetSalary;
public:
Salary(string d, double b, string n, int i) :Person(n,i)
{
designation = d;
basic = b;
}
void acceptSalaryDetails()
{
AcceptPersonDetails();
cout << "Enter Designation: ";
getline(cin,designation);
};
int main()
{
Salary emp1;
emp1.acceptSalaryDetails();
cout << "\nEmployee Details: " << endl;
emp1.displaySalaryDetails();
Salary emp2("kuh",45000,"deepa",43);
emp2.calculation();
emp2.displaySalaryDetails();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
// Constructor for Person class
Person(const string& n, int a) : name(n), age(a) {}
int main() {
// Create a student object with sample data
Student student("Madhav", 20, 38, "BCA");
return 0;
}
/*Q3. Implement the following type of inheritance. Create appropriate class,
datamembers and
member functions to accept the values from the user and display the student details
along
with the final grade depending upon the marks scored. */
#include <iostream>
#include <string>
using namespace std;
class Student {
protected:
int roll;
string branch;
public:
// Constructor to accept student details
Student() {
cout << "Enter roll no: ";
cin >> roll;
cout << "Enter branch: ";
cin >> branch;
}
};
public:
// Constructor to calculate total marks and determine grade
Result() {
total_theory = theory_mark1 + theory_mark2;
total_lab = lab_mark1 + lab_mark2;
grade = calculateGrade();
}
int main() {
// Create Result object and display student result
Result studentResult;
studentResult.display();
return 0;
}
ASSIGNMENT:-11
#include<iostream>
#include<string>
using namespace std;
class Person
{
protected:
string name;
int id;
string designation;
public:
void Accept_Person_Details()
{
cout << "Enter Name: ";
getline(cin,name);
void displayAccountDetails()
{
cout << "Salary: " << salary << endl;
}
};
void Accept_Details()
{
Accept_Person_Details();
Accept_Account_Details();
Accept_HR_Details();
calculate_Grade();
}
void Display_Details()
{
displayPersonDetails();
displayAccountDetails();
displayHRDetails();
cout << "Grade: " << grade << endl;
}
};
int main()
{
Position emp;
emp.Accept_Details();
cout << "\nEmployee Details: " << endl;
emp.Display_Details();
return 0;
}
#include<iostream>
#include<string>
using namespace std;
class Book
{
protected:
string BName;
int Bid;
public:
void Accept_Book_Details()
{
cout << "Enter Book Name: ";
getline(cin,BName);
void displayBookDetails()
{
cout << "Author: " << Author << endl;
cout << "Number of Pages: " << no_of_pages << endl;
cout << "Type: " << type << endl;
}
};
class Price : virtual public Book
{
protected:
double Actual_price;
double Discount_price;
public:
void Accept_Price_Details()
{
cout << "Enter Actual price: ";
cin >> Actual_price;
void displayPriceDetails()
{
cout << "Actual price: " << Actual_price << endl;
cout << "Discount Price: " << Discount_price << endl;
}
};
class Region : public BookDetail, public Price
{
protected:
string country;
public:
void Accept_Region_Details()
{
cin.ignore();
cout << "Enter Country: ";
getline(cin,country);
}
/*Q3: A bank maintains two kinds of accounts for customers, savings and current
account. The savings account provides compound interest and withdrawal facility,
check
book facility. Current account provides check book facility but no interest.Current
account holders should maintain a minimum balance of Rs. 100/-. Write a program to
create a class account that stores customer name account number and account type.
From this derive two classes curr_act for current account, save_act for savings
account.
include necessary member functions to accept required data through constructor and
performing transactions and to check the balance*/
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
class Account
{
protected:
string customer_name;
int account_number;
string account_type;
double balance;
public:
//constructor to initialize common account details
Account(string name, int acc_num, string type, double initial_balance)
{
customer_name = name;
account_number = acc_num;
account_type = type;
balance = initial_balance;
}
Save_Act savings_account("deepa",102,1000.0,5.0);
savings_account.display_Details();
savings_account.deposit(300);
savings_account.withdraw(200);
savings_account.calculate_Interest(2);
return 0;
}
// Assignment-12 (Polymorphism)
/*Q1. Write a program to create a class named figure which should have one member
function
to compute the area of the figure and one member variable to store the area value.
Derive
two classes rectangle and triangle to accept (length, breadth) and (base, height).
Calculate area of two figures.
Make the base class function to compute the area a virtual function
and redefine it in the derived classes. Use pointer to base class concept.
--> Add required functions to compute the perimeter in the similar way the area is
calculated.
--> Compare the perimeter of both figures.
--> Compare the area of both figures.*/
#include <iostream>
#include <cmath>
using namespace std;
class Figure {
protected:
double area;
public:
virtual double computeArea() = 0;
virtual double computePerimeter() = 0;
virtual ~Figure() {} // Virtual destructor
};
double computeArea() {
area = length * breadth;
return area;
}
double computePerimeter() {
return 2 * (length + breadth);
}
private:
double length, breadth;
};
double computeArea() {
area = 0.5 * base * height;
return area;
}
double computePerimeter() {
return base + height + sqrt(base * base + height * height); // Assuming
it's a right triangle
}
private:
double base, height;
};
int main() {
Figure* figure1 = new Rectangle(5, 3);
Figure* figure2 = new Triangle(4, 3);
delete figure1;
delete figure2;
return 0;
}
// Assignment-13(Polymorphism)
/*Q1. Write a program to accept two numbers in the base class through constructor.
Derive two classes square and cube to calculate the sum of their squares and cubes.
Use appropriate constructor to accept the number and display function to display
the result.
Use the concepts of dynamic polymorphism.*/
#include <iostream>
using namespace std;
class Number {
protected:
double num1, num2;
public:
Number(double n1, double n2) : num1(n1), num2(n2) {}
virtual void compute() = 0; // Pure virtual function for computation
virtual void display() = 0; // Pure virtual function for display
virtual ~Number() {} // Virtual destructor
};
int main() {
double num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
squareCalc->compute();
squareCalc->display();
cubeCalc->compute();
cubeCalc->display();
delete squareCalc;
delete cubeCalc;
return 0;
}
/*Q2. Prove that the objects of a class containing virtual functions are larger in
size by 1 byte to
store the address of the virtual table. Write a program using virtual function to
demonstrate the same.*/
#include <iostream>
using namespace std;
class BaseNotVirtual {
public:
int a;
double b;
};
class BaseVirtual {
public:
int a;
double b;
virtual void func() {}
};
int main() {
BaseNotVirtual obj1;
BaseVirtual obj2;
cout << "Size of object without virtual function: " << sizeof(obj1) << " bytes"
<< endl;
cout << "Size of object with virtual function: " << sizeof(obj2) << " bytes" <<
endl;
return 0;
}