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

Lab Report 4

Uploaded by

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

Lab Report 4

Uploaded by

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

DEPARTMENT OF COMPUTER & SOFTWARE

ENGINEERING
COLLEGE OF E&ME, NUST, RAWALPINDI

EC-201 Object Oriented Programming

LAB MANUAL – 04

Course Instructor: Lec Anum Abdul Salam

Lab Instructor: LE Eman Fatima

Student Name: Fabeha Zahid Mahmood

Degree/ Syndicate: 45 / B
LAB # 04: Constant and Static Data Members
Tool Used: Visual Studio 2019
LAB TASKS:

1. Create a class Job. where every job has a deadline and a profit. Profit can be earned only if the
job is finished before the deadline. There is a fixed deadline associated with a particular job.
Each job has a JobID which increments on creation of new Job. E.g. for the 1st instance the
JobID will be 1 and for the second it should automatically set to 2. It is also given that every
job takes a single unit of time, so the minimum possible deadline for any job is 1. Write the
functions that calculate the total profit if all the jobs have been performed depending upon
whether it was completed in time or not. Declare constant, static Data members accordingly
where required.
UML Diagram:

Source Code:
#include <iostream>
using namespace std;

class Job {
private:
// Constant attributes
const int jobID;
const int deadline;
// Variable attribute
int timetaken;
// Static attribute to track job count
static int count;

public:
// Constructor (parameterized)
Job(int d, int tt) : jobID(count), deadline(d), timetaken(tt) {
count++; // Increment job count for each new job
}

// Setters
void settime(int tt) {
timetaken = tt;
}

// Getters
int getjobID() const {
return jobID;
}

int getdeadline() const {


return deadline;
}

// Validate deadline
int validate_dd() const {
return (deadline >= 1) ? 0 : 1; // Change here to remove parameter
}

// Calculate profit based on whether job is completed on time


float calcprofit() {
if (timetaken <= deadline) {
return ((deadline - timetaken) / static_cast<float>(deadline)) *
100; // Use static_cast for accurate division
}
else {
return 0;
}
}

static float totalprofit(Job* jobs[], int numJobs) {


float total = 0;
for (int i = 0; i < numJobs; i++) {
Job jobTemp = *jobs[i]; // Dereference pointer to create a Job
object
total += jobTemp.calcprofit(); // Add profit for each job
}
return total;
}
};

// Initialize static member


int Job::count = 1;

int main() {
const int numJobs = 10; // Number of jobs
Job* arr[numJobs]; // Array to store job pointers

// Input job details (deadline and time taken)


for (int i = 0; i < numJobs; i++) {
int d, tt;
cout << "Enter deadline for job " << (i + 1) << ": ";
cin >> d;
cout << "Enter timetaken to complete job " << (i + 1) << ": ";
cin >> tt;

// Validate deadline
Job tempjob(d, tt);
if (tempjob.validate_dd()) { // Call the method directly
cout << "Invalid deadline for job " << (i + 1) << ". Deadline
should be at least 1." << endl;
i--; // Retry this job
}
else {
arr[i] = new Job(d, tt); // Create new job
}
}

// Calculate and display total profit


float total = Job::totalprofit(arr, numJobs);
cout << "Total profit: " << total << endl;

// Clean up dynamically allocated memory


for (int i = 0; i < numJobs; i++) {
delete arr[i];
}

return 0;
}

Output:
2. Define a class Book that has a static data member to keep track of the number of books created.
The class should also have a constant member function to display the details of the book
without modifying them. Create multiple Book objects and display the number of books
created using the static member function.

UML Diagram:

Source Code:
#include <iostream>
#include <string>
using namespace std;

class Book {
private:
static int num_books;
string title;
string author;
int pages;
string publisher;
string price;

public:
///////////////setters//////////////
void set_title(const string& t) { title = t; }
void set_author(const string& a) { author = a; }
void set_publisher(const string& pub) { publisher = pub; }
void set_pages(int p) {
if (p > 0) {
pages = p;
}
else {
cout << "Pages must be a positive number." << endl;
}
}
void set_price(const string& pr) { price = pr; }

/////////////////getters/////////////
string get_title() const { return title; }
string get_author() const { return author; }
string get_publisher() const { return publisher; }
int get_pages() const { return pages; }
string get_price() const { return price; }

//////////default constructor/////////
Book() : title("unknown"), author("unknown"), publisher("unknown"), pages(0),
price("Rs. 0") {
num_books++;
}

//////////parameterized constructor/////////
Book(string t, string a, int p, string pub, string pr)
: title(t), author(a), pages(p), publisher(pub), price(pr) {
num_books++;
}

/////////////////Destructor//////////////////
~Book() { num_books--; }

/////////////////Display function//////////////
void display_details() const {
if (title == "unknown") {
cout << "Book details (initially):" << endl; // Message for the
default book
}
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Pages: " << pages << endl;
cout << "Publisher: " << publisher << endl;
cout << "Price: " << price << endl;
}

////////////static function for amount of books/////////


static int get_book_count() {
return num_books;
}
};

// Initialize the static member variable


int Book::num_books = 0;

int main() {
// Object instantiation
Book book_1; // Calling default constructor
Book book_2("Harry Potter and the Goblet of Fire", "J.K. Rowling", 636,
"Bloomsbury", "Rs. 599/-"); // Calling parameterized constructor
Book book_3("The Invisible Life of Addie Larue", "V.E. Schwab", 448, "Tor",
"Rs. 1500/-");

// Displaying details of the books


book_1.display_details();
cout << endl;
// Modifying book_1 details
book_1.set_title("A Little Life");
book_1.set_author("Hanya Vanigahara");
book_1.set_pages(832);
book_1.set_publisher("Double Day");
book_1.set_price("Rs. 549/-");

// Display modified details of book_1


cout << "Updated details for book_1:" << endl;
book_1.display_details();
cout << endl;

book_2.display_details();
cout << endl;

book_3.display_details();
cout << endl;

// Display total number of books created


cout << "Total number of books: " << Book::get_book_count() << endl;

return 0;
}

Output:
3. (a) Define a class Customer that includes a customer name of type string, a constant customer
ID of type int, and a string array of size 5 to store items purchased by the customer. Implement
a parameterized constructor that takes the customer’s name and automatically assigns an ID
starting from the first four digits of your roll no incrementing with each new object. Include a
copy constructor, a destructor, and provide getters and setters for the customer’s name,
individual items by index, and the entire items array. Ensure that all functions that do not
modify data members are marked as constant.

UML Diagram:

Source Code:
#include<iostream>
using namespace std;

class Customer {
private:
// Private attributes of class Customer
string name;
string items[5];
const int ID;
static int roll_num;

public:
// Parameterized constructor
Customer(const string& c_name, string c_items[5]) : name(c_name),
ID(roll_num++) {
for (int i = 0; i < 5; i++) {
items[i] = c_items[i];
}
}

// Copy constructor
Customer(const Customer& other) : name(other.name), ID(other.ID) {
for (int i = 0; i < 5; i++) {
items[i] = other.items[i]; // Copy each item
}
}
// Getters
string get_name() const {
return name;
}

int get_ID() const {


return ID;
}

string getItem(int index) const {


if ((index >= 0) && (index < 5)) {
return items[index];
}
else {
return ""; // Invalid index
}
}

// Setters
void set_name(const string& newName) {
name = newName;
}

void set_item(int index, const string& new_item) {


if (index >= 0 && index < 5) {
items[index] = new_item;
}
}

// Destructor
~Customer() {
cout << "Customer with ID " << ID << " is being deleted." << endl;
}
};
// Initialize static variable
int Customer::roll_num = 1234;
int main() {
string items_c1[5] = { "Eggs", "Bread", "Milk", "Chicken", "Butter" };
string items_c2[5] = { "Sugar", "Bread", "Milk", "Chicken", "Butter" };

// Creating objects using parameterized constructor


Customer C1("Saad", items_c1);
Customer C2("Faqiha", items_c2);

// Using copy constructor


Customer C3 = C1;

// Display customer info


cout << "Customer C1 ID: " << C1.get_ID() << ", Name: " << C1.get_name() <<
endl;
cout << "Customer C3 ID (Copy of C1): " << C3.get_ID() << ", Name: " <<
C3.get_name() << endl;

// Set new name for C1


C1.set_name("Hamza");
cout << "Updated C1 Name: " << C1.get_name() << endl;

// Get and set individual items


cout << "C1 First Item: " << C1.getItem(0) << endl;
C1.set_item(0, "Orange Juice");
cout << "Updated C1 First Item: " << C1.getItem(0) << endl;
return 0; }
Output:

(b) Add a private static integer member to the Customer class to track the total number of
customer objects created. This static member should be incremented when an object is created
and decremented when an object is destroyed. Provide a public static function to access this
count. In the main function, instantiate three Customer objects and use the static function to
output the total count of customer objects. Then, call the destructor for one of the objects and
display the updated count. Additionally, create a constant Customer object and comment on
which functions can be called on it and which cannot, explaining the reasons.
UML Diagram:

Source Code:

#include<iostream>
using namespace std;

class Customer {
private:
// Private attributes of class Customer
string name;
string items[5];
const int ID;
static int roll_num;
static int customer_count;

public:
// Parameterized constructor
Customer(const string& c_name, string c_items[5]) : name(c_name),
ID(roll_num++) {
for (int i = 0; i < 5; i++) {
items[i] = c_items[i];
}
customer_count++;
}

// Copy constructor
Customer(const Customer& other) : name(other.name), ID(other.ID) {
for (int i = 0; i < 5; i++) {
items[i] = other.items[i]; // Copy each item
}
customer_count++;
}

// Getters
string get_name() const {
return name;
}

int get_ID() const {


return ID;
}

string getItem(int index) const {


if ((index >= 0) && (index < 5)) {
return items[index];
}
else {
return ""; // Invalid index
}
}

// Setters
void set_name(const string& newName) {
name = newName;
}

void set_item(int index, const string& new_item) {


if (index >= 0 && index < 5) {
items[index] = new_item;
}
}

//static count function


static int get_cutomer_count() {
return customer_count;
}

// Destructor
~Customer() {
cout << "Customer with ID " << ID << " is being deleted." << endl;
customer_count--;
}
};
// Initialize static variable
int Customer::roll_num = 1234;
int Customer::customer_count = 0;

int main() {
string items_c1[5] = { "Eggs", "Bread", "Milk", "Chicken", "Butter" };
string items_c2[5] = { "Sugar", "Bread", "Milk", "Chicken", "Butter" };

// Creating objects using parameterized constructor


Customer C1("Saad", items_c1);
Customer C2("Faqiha", items_c2);

// Using copy constructor


Customer C3 = C1;

//Total customers after creation of C3


cout << "Total customers after creating C3: " <<
Customer::get_cutomer_count() << "\n";

//Calling the destructor


C2.~Customer();

//Total customers after creation of C3


cout << "Total customers after calling destructor: " <<
Customer::get_cutomer_count() << "\n";

//constant object creation


const Customer C4("Momina", items_c2);
// only const member functions can be called which are get_name and get_ID.
//Non-const member functions like set_name() are not allowed since they might
modify the object, violating its constant nature

return 0;
}

Output:
Think Tank:
1. Which objects can call the const functions?
Const functions can be called by the following:
 Const objects: These objects can only call const member functions because they cannot
modify the object's data.
 Non-const objects: These objects can call both const and non-const member functions, as
they are allowed to modify the object's state.

2. What will happen if a const object calls a non-const member function?

If a const object tries to call a non-const member function, it will cause a compilation error. This
happens because non-const functions can change the object's data, which isn’t allowed for const
objects. The compiler stops this to keep the const object unchanged.

3. Can a function have both the const and non-const version in the same program?

Yes, a function can have both const and non-const versions in the same program. This is known
as function overloading.

You might also like