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

TP oop with c++

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, using a 'Car' class as an example to illustrate class definition, object creation, and member function access. It also introduces the <vector> library for dynamic arrays, detailing its features and providing example code for managing a collection of integers. Additionally, it includes exercises for creating classes for an e-commerce application and a chat application, complete with C++ implementations for each class.

Uploaded by

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

TP oop with c++

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, using a 'Car' class as an example to illustrate class definition, object creation, and member function access. It also introduces the <vector> library for dynamic arrays, detailing its features and providing example code for managing a collection of integers. Additionally, it includes exercises for creating classes for an e-commerce application and a chat application, complete with C++ implementations for each class.

Uploaded by

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

To illustrate the concepts of OOP, let's consider an example of a class called "Car.

" A
car can have properties such as color, brand, and model, and it can perform actions
like starting, stopping, and accelerating.
Step 1: Defining a Class
In C++, a class is defined using the class keyword, followed by the class name.
Here's an example of the Car class:
class Car {
public:
// Member variables (properties)
string color;
string brand;
string model;

// Member functions (actions)


void start() {
cout << "The car has started.\n";
}

void stop() {
cout << "The car has stopped.\n";
}

void accelerate() {
cout << "The car is accelerating.\n";
}
};

In the above code, the Car class has three member variables (color, brand, and model)
and three member functions (start, stop, and accelerate). The public keyword
before the member variables and functions specifies their access level, allowing them
to be accessed from outside the class.
Step 2: Creating Objects (Instances)
Once we have defined a class, we can create objects (instances) of that class. Objects
are created using the class name followed by parentheses. Here's an example:
Car myCar; // Creating a Car object called "myCar"

Step 3: Accessing Member Variables and Functions


To access the member variables and functions of an object, we use the dot (.)
operator. Here's how we can access the properties and actions of the myCar object:
myCar.color = "Red"; // Setting the color property of myCar
myCar.brand = "Toyota"; // Setting the brand property of myCar
myCar.model = "Camry"; // Setting the model property of myCar

myCar.start(); // Calling the start() function of myCar


myCar.accelerate(); // Calling the accelerate() function of myCar
myCar.stop(); // Calling the stop() function of myCar

Dr TABUEU FOTSO Laurent Cabrel


Step 4: Creating Multiple Objects
We can create multiple objects of the same class, each with its own set of properties
and actions. For example:
Car friendCar; // Creating another Car object called "friendCar"

friendCar.color = "Blue";
friendCar.brand = "Ford";
friendCar.model = "Mustang";

friendCar.start();
friendCar.accelerate();
friendCar.stop();

By creating multiple objects, we can represent different entities or instances of the


same class.
That's a brief overview of OOP in C++. We have covered defining classes, creating
objects, and accessing member variables and functions. Remember, this is just the tip
of the iceberg when it comes to OOP

Note : <vector> library


In C++, the <vector> library provides the vector container, which is a dynamic array-like
structure that can store multiple elements of the same type. Here's an explanation of some key
features and functionalities of the <vector> library:

1. Dynamic Size: Unlike static arrays, vectors automatically manage their size and can grow or
shrink as elements are added or removed. This makes them more flexible and convenient to
work with.
2. Element Access: Elements in a vector are accessed using zero-based indexing. You can use
the subscript operator ([]) to access individual elements or use the at() function, which
performs bounds checking and throws an exception if the index is out of range.
3. Insertion and Deletion: Vectors provide functions to insert or remove elements at specific
positions. The push_back() function adds an element to the end of the vector, increasing
its size. The pop_back() function removes the last element from the vector, reducing its
size. Additionally, you can use insert() and erase() functions to insert or remove
elements at any position within the vector.
4. Size and Capacity: The size() function returns the number of elements currently stored in
the vector. The capacity() function returns the maximum number of elements that the
vector can hold without needing to resize its internal storage. If more elements are added
beyond the current capacity, the vector automatically reallocates memory to accommodate
the new elements.

Dr TABUEU FOTSO Laurent Cabrel


5. Iteration: Vectors can be traversed using iterators. The begin() function returns an iterator
pointing to the first element, and the end() function returns an iterator pointing to the
position just after the last element. You can use iterators in combination with loops to iterate
over the vector's elements.
6. Range-based For Loop: C++11 introduced the range-based for loop, which simplifies
iteration over all elements of a vector. It allows you to directly access each element without
the need for explicit iterators.

Let's explore some example usage of the <vector> library with int elements.
Here's an updated code snippet that demonstrates various functions of the
<vector> library:
cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
// Create an empty vector of integers
vector<int> numbers;

// Add elements to the vector using push_back()


numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

// Access elements using subscript operator []


cout << "First element: " << numbers[0] << endl;
cout << "Second element: " << numbers[1] << endl;
cout << "Third element: " << numbers[2] << endl;

// Modify elements using subscript operator []


numbers[1] = 25;

// Get the size of the vector


cout << "Size of the vector: " << numbers.size() << endl;

// Iterate over the elements using a range-based for loop


cout << "Elements of the vector: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

// Insert an element at a specific position


numbers.insert(numbers.begin() + 1, 15);

// Remove an element at a specific position


numbers.erase(numbers.begin());

// Check if the vector is empty


if (numbers.empty()) {
cout << "Vector is empty" << endl;
} else {
cout << "Vector is not empty" << endl;

Dr TABUEU FOTSO Laurent Cabrel


}

// Clear all elements from the vector


numbers.clear();

// Check the new size of the vector


cout << "Size of the vector after clearing: " << numbers.size() << endl;

return 0;
}

In this example, we create a vector called numbers to store integer elements. We add
elements using push_back(), access and modify elements using the subscript operator [],
get the size of the vector using size(), and iterate over the elements using a range-based for
loop. We also demonstrate inserting and erasing elements at specific positions using
insert() and erase() functions. Additionally, we check if the vector is empty using
empty() and clear all elements using clear().

Exercise 1: E-commerce App


Class: Product
Attributes:
• id (int): the unique identifier of the product
• name (string): the name of the product
• price (double): the price of the product
• quantity (int): the available quantity of the product
Methods:
• Constructor: initializes the attributes of the product
• Getters and setters: to access and modify the attributes of the product
• DecreaseQuantity(amount: int): reduces the quantity of the product by the given amount
• IncreaseQuantity(amount: int): increases the quantity of the product by the given amount
Class: Cart
Attributes:
• products (vector<Product>): a collection of products added to the cart
Methods:
• AddToCart(product: Product): adds a product to the cart
• RemoveFromCart(product: Product): removes a product from the cart
• Checkout(): completes the purchase and clears the cart
Class: Order
Attributes:
• id (int): the unique identifier of the order
• products (vector<Product>): a collection of products in the order

Dr TABUEU FOTSO Laurent Cabrel


• totalAmount (double): the total amount to be paid for the order
• status (string): the status of the order (e.g., pending, shipped, delivered)
Methods:
• Constructor: initializes the attributes of the order
• Getters and setters: to access and modify the attributes of the order
• AddProduct(product: Product): adds a product to the order
• RemoveProduct(product: Product): removes a product from the order
• UpdateStatus(status: string): updates the status of the order
Association: The Cart class is associated with the Product class, as it contains a collection of
Product objects. The Order class is also associated with the Product class, as it contains a collection
of Product objects.

Solution
A solution code in C++ that implements the classes and methods we discussed:
#include <iostream>
#include <vector>
using namespace std;

class Product {
private:
int id;
string name;
double price;
int quantity;
public:
Product(int id, string name, double price, int quantity) {
this->id = id;
this->name = name;
this->price = price;
this->quantity = quantity;
}

void decreaseQuantity(int amount) {


quantity -= amount;
}

void increaseQuantity(int amount) {


quantity += amount;
}

int getId() {
return id;
}

string getName() {
return name;
}

double getPrice() {
return price;
}

Dr TABUEU FOTSO Laurent Cabrel


int getQuantity() {
return quantity;
}
};

class Cart {
private:
vector<Product> products;
public:
void addToCart(Product product) {
products.push_back(product);
}

void removeFromCart(Product product) {


for (int i = 0; i < products.size(); i++) {
if (products[i].getId() == product.getId()) {
products.erase(products.begin() + i);
break;
}
}
}

void checkout() {
// Perform the necessary operations to complete the purchase
// Clear the cart after checkout
products.clear();
}
};

class Order {
private:
int id;
vector<Product> products;
double totalAmount;
string status;
public:
Order(int id, vector<Product> products, double totalAmount, string status) {
this->id = id;
this->products = products;
this->totalAmount = totalAmount;
this->status = status;
}

void addProduct(Product product) {


products.push_back(product);
}

void removeProduct(Product product) {


for (int i = 0; i < products.size(); i++) {
if (products[i].getId() == product.getId()) {
products.erase(products.begin() + i);
break;
}
}
}

void updateStatus(string status) {


this->status = status;
}

Dr TABUEU FOTSO Laurent Cabrel


int getId() {
return id;
}

vector<Product> getProducts() {
return products;
}

double getTotalAmount() {
return totalAmount;
}

string getStatus() {
return status;
}
};

int main() {
// Sample usage of the classes and methods
Product product1(1, "iPhone", 999.99, 10);
Product product2(2, "Samsung Galaxy", 799.99, 8);

Cart cart;
cart.addToCart(product1);
cart.addToCart(product2);

Order order(1, cart.getProducts(), 1799.98, "Pending");


order.updateStatus("Shipped");

cout << "Order ID: " << order.getId() << endl;


cout << "Products in Order: " << endl;
vector<Product> orderProducts = order.getProducts();
for (int i = 0; i < orderProducts.size(); i++) {
cout << "Name: " << orderProducts[i].getName() << ", Price: $" <<
orderProducts[i].getPrice() << endl;
}
cout << "Total Amount: $" << order.getTotalAmount() << endl;
cout << "Status: " << order.getStatus() << endl;

return 0;
}

Exercise 2: Chat App


Class: User
Attributes:
• id (int): the unique identifier of the user
• username (string): the username of the user
Methods:
• Constructor: initializes the attributes of the user
• Getters and setters: to access and modify the attributes of the user

Dr TABUEU FOTSO Laurent Cabrel


Class: Message
Attributes:
• id (int): the unique identifier of the message
• sender (User): the user who sent the message
• receiver (User): the user who receives the message
• content (string): the content of the message
• timestamp (datetime): the timestamp when the message was sent
Methods:
• Constructor: initializes the attributes of the message
• Getters and setters: to access and modify the attributes of the message
Class: Chat
Attributes:
• id (int): the unique identifier of the chat
• users (vector<User>): the users participating in the chat
• messages (vector<Message>): the messages exchanged in the chat
Methods:
• AddUser(user: User): adds a user to the chat
• RemoveUser(user: User): removes a user from the chat
• SendMessage(sender: User, receiver: User, content: string): sends a message in the chat
Association: The Chat class is associated with the User class, as it contains a collection of User
objects. The Message class is associated with the User class, as it contains sender and receiver
objects of the User class.

C++ implementation of the classes User, Message, and Chat based on the provided
specifications:
cpp
#include <iostream>
#include <vector>
#include <string>
#include <ctime>

using namespace std;

// User class
class User {
private:
int id;
string username;

public:
User(int id, string username) {

Dr TABUEU FOTSO Laurent Cabrel


this->id = id;
this->username = username;
}

int getId() {
return id;
}

string getUsername() {
return username;
}

void setUsername(string newUsername) {


username = newUsername;
}
};

// Message class
class Message {
private:
int id;
User sender;
User receiver;
string content;
time_t timestamp;

public:
Message(int id, User sender, User receiver, string content) {
this->id = id;
this->sender = sender;
this->receiver = receiver;
this->content = content;
this->timestamp = time(0); // Current timestamp
}

int getId() {
return id;
}

User getSender() {
return sender;
}

User getReceiver() {
return receiver;
}

string getContent() {
return content;
}

time_t getTimestamp() {
return timestamp;
}
};

// Chat class
class Chat {
private:
int id;
vector<User> users;

Dr TABUEU FOTSO Laurent Cabrel


vector<Message> messages;

public:
Chat(int id) {
this->id = id;
}

void addUser(User user) {


users.push_back(user);
}

void removeUser(User user) {


for (int i = 0; i < users.size(); i++) {
if (users[i].getId() == user.getId()) {
users.erase(users.begin() + i);
break;
}
}
}

void sendMessage(User sender, User receiver, string content) {


Message message(messages.size() + 1, sender, receiver, content);
messages.push_back(message);
}
};

int main() {
// Creating users
User user1(1, "Alice");
User user2(2, "Bob");

// Creating a chat
Chat chat(1);

// Adding users to the chat


chat.addUser(user1);
chat.addUser(user2);

// Sending a message
chat.sendMessage(user1, user2, "Hello, how are you?");

// Displaying the messages in the chat


vector<Message> messages = chat.getMessages();
for (Message message : messages) {
cout << "Sender: " << message.getSender().getUsername() << endl;
cout << "Receiver: " << message.getReceiver().getUsername() << endl;
cout << "Content: " << message.getContent() << endl;
cout << "Timestamp: " << ctime(&message.getTimestamp()) << endl;
cout << endl;
}

return 0;
}

In this implementation, we have defined the User, Message, and Chat classes. The User class
has attributes id and username, along with getters and setters to access and modify these
attributes. The Message class has attributes id, sender, receiver, content, and
timestamp, along with respective getters. The Chat class has attributes id, users, and
messages, along with methods to add users, remove users, and send messages in the chat.

Dr TABUEU FOTSO Laurent Cabrel


In the main function, we create two users, user1 and user2, and a chat chat. We add the users
to the chat using the addUser method and send a message from user1 to user2 using the
sendMessage method. Finally, we display the messages in the chat using a loop and the getters of
the Message class.

Exercise 3: E-Learning
Class: Course
Attributes:
• id (int): the unique identifier of the course
• name (string): the name of the course
• instructor (string): the name of the instructor
• students (vector<string>): the names of the students enrolled in the course
Methods:
• Constructor: initializes the attributes of the course
• Getters and setters: to access and modify the attributes of the course
• AddStudent(student: string): adds a student to the course
• RemoveStudent(student: string): removes a student from the course
Class: Student
Attributes:
• id (int): the unique identifier of the student
• name (string): the name of the student
• courses (vector<Course>): the courses in which the student is enrolled
Methods:
• Constructor: initializes the attributes of the student
• Getters and setters: to access and modify the attributes of the student
• EnrollCourse(course: Course): enrolls the student in a course
• WithdrawCourse(course: Course): withdraws the student from a course
Association: The Course class is associated with the Student class, as it contains a collection of
Student objects. The Student class is also associated with the Course class, as it contains a
collection of Course objects.

C++ implementation of the classes Course and Student based on the provided specifications:

cpp
#include <iostream>
#include <vector>
#include <string>

using namespace std;

Dr TABUEU FOTSO Laurent Cabrel


// Course class
class Course {
private:
int id;
string name;
string instructor;
vector<string> students;

public:
Course(int id, string name, string instructor) {
this->id = id;
this->name = name;
this->instructor = instructor;
}

int getId() {
return id;
}

string getName() {
return name;
}

string getInstructor() {
return instructor;
}

void setName(string newName) {


name = newName;
}

void setInstructor(string newInstructor) {


instructor = newInstructor;
}

void addStudent(string student) {


students.push_back(student);
}

void removeStudent(string student) {


for (int i = 0; i < students.size(); i++) {
if (students[i] == student) {
students.erase(students.begin() + i);
break;
}
}
}
};

// Student class
class Student {
private:
int id;
string name;
vector<Course> courses;

public:
Student(int id, string name) {
this->id = id;
this->name = name;

Dr TABUEU FOTSO Laurent Cabrel


}

int getId() {
return id;
}

string getName() {
return name;
}

void setName(string newName) {


name = newName;
}

void enrollCourse(Course course) {


courses.push_back(course);
}

void withdrawCourse(Course course) {


for (int i = 0; i < courses.size(); i++) {
if (courses[i].getId() == course.getId()) {
courses.erase(courses.begin() + i);
break;
}
}
}
};

int main() {
// Creating courses
Course course1(1, "Mathematics", "Prof. Smith");
Course course2(2, "Physics", "Prof. Johnson");

// Creating students
Student student1(1, "Alice");
Student student2(2, "Bob");

// Enrolling students in courses


student1.enrollCourse(course1);
student1.enrollCourse(course2);
student2.enrollCourse(course2);

// Adding students to courses


course1.addStudent(student1.getName());
course2.addStudent(student1.getName());
course2.addStudent(student2.getName());

// Withdrawing a student from a course


student1.withdrawCourse(course1);

// Displaying the enrolled courses of a student


cout << "Courses enrolled by " << student1.getName() << ":" << endl;
vector<Course> enrolledCourses = student1.getCourses();
for (Course course : enrolledCourses) {
cout << "- " << course.getName() << " (Instructor: " <<
course.getInstructor() << ")" << endl;
}

// Displaying the students in a course


cout << "Students in " << course2.getName() << ":" << endl;
vector<string> enrolledStudents = course2.getStudents();

Dr TABUEU FOTSO Laurent Cabrel


for (string student : enrolledStudents) {
cout << "- " << student << endl;
}

return 0;
}

In this implementation, we have defined the Course and Student classes. The Course class
has attributes id, name, instructor, and students, along with respective getters and setters.
It also has methods to add and remove students from the course. The Student class has attributes
id, name, and courses, along with respective getters and setters. It also has methods to enroll in
and withdraw from courses.
In the main function, we create two courses, course1 and course2, and two students,
student1 and student2. We enroll student1 in both courses and student2 in course2.
We add the students to the respective courses using the addStudent method. We then withdraw
student1 from course1 using the withdrawCourse method. Finally, we display the
enrolled courses of student1 and the students in course2 using loops and the getters of the
respective classes.

Exercise 4: Booking Car


Class: Car
Attributes:
• id (int): the unique identifier of the car
• brand (string): the brand of the car
• model (string): the model of the car
• available (bool): whether the car is available for booking or not
Methods:
• Constructor: initializes the attributes of the car
• Getters and setters: to access and modify the attributes of the car
• BookCar(): books theI apologize for the incomplete response. Here is the continuation of the
exercise:
Methods:
• Constructor: initializes the attributes of the car
• Getters and setters: to access and modify the attributes of the car
• BookCar(): books the car by marking it as unavailable
• ReleaseCar(): releases the car by marking it as available
Class: Customer
Attributes:
• id (int): the unique identifier of the customer
• name (string): the name of the customer

Dr TABUEU FOTSO Laurent Cabrel


• phoneNumber (string): the phone number of the customer
• bookedCar (Car): the car booked by the customer
Methods:
• Constructor: initializes the attributes of the customer
• Getters and setters: to access and modify the attributes of the customer
• BookCar(car:Car): books a car for the customer by assigning it to the bookedCar attribute
• ReleaseCar(): releases the car booked by the customer by setting the bookedCar attribute to
null
Association: The Customer class is associated with the Car class, as it contains a bookedCar object
of the Car class.

C++ implementation of the classes Car and Customer based on the provided specifications:

cpp
#include <iostream>
#include <string>

using namespace std;

// Car class
class Car {
private:
int id;
string brand;
string model;
bool available;

public:
Car(int id, string brand, string model) {
this->id = id;
this->brand = brand;
this->model = model;
this->available = true;
}

int getId() {
return id;
}

string getBrand() {
return brand;
}

string getModel() {
return model;
}

bool isAvailable() {
return available;
}

void setBrand(string newBrand) {


brand = newBrand;

Dr TABUEU FOTSO Laurent Cabrel


}

void setModel(string newModel) {


model = newModel;
}

void bookCar() {
available = false;
}

void releaseCar() {
available = true;
}
};

// Customer class
class Customer {
private:
int id;
string name;
string phoneNumber;
Car* bookedCar;

public:
Customer(int id, string name, string phoneNumber) {
this->id = id;
this->name = name;
this->phoneNumber = phoneNumber;
this->bookedCar = nullptr;
}

int getId() {
return id;
}

string getName() {
return name;
}

string getPhoneNumber() {
return phoneNumber;
}

Car* getBookedCar() {
return bookedCar;
}

void setName(string newName) {


name = newName;
}

void setPhoneNumber(string newPhoneNumber) {


phoneNumber = newPhoneNumber;
}

void bookCar(Car* car) {


bookedCar = car;
car->bookCar();
}

void releaseCar() {

Dr TABUEU FOTSO Laurent Cabrel


if (bookedCar != nullptr) {
bookedCar->releaseCar();
bookedCar = nullptr;
}
}
};

int main() {
// Creating cars
Car car1(1, "Toyota", "Camry");
Car car2(2, "Honda", "Civic");

// Creating a customer
Customer customer(1, "Alice", "1234567890");

// Booking a car for the customer


customer.bookCar(&car1);

// Checking the availability of the car


cout << "Car 1 availability: " << (car1.isAvailable() ? "Available" : "Not
Available") << endl;

// Checking the booked car of the customer


cout << "Customer's booked car: ";
if (customer.getBookedCar() != nullptr) {
cout << customer.getBookedCar()->getBrand() << " " <<
customer.getBookedCar()->getModel() << endl;
} else {
cout << "None" << endl;
}

// Releasing the car


customer.releaseCar();

// Checking the availability of the car after releasing


cout << "Car 1 availability after releasing: " << (car1.isAvailable() ?
"Available" : "Not Available") << endl;

return 0;
}

In this implementation, we have defined the Car and Customer classes. The Car class has
attributes id, brand, model, and available, along with respective getters and setters. It also
has methods to book and release the car by modifying the available attribute. The Customer
class has attributes id, name, phoneNumber, and bookedCar, along with respective getters
and setters. It also has methods to book and release a car by assigning or setting the bookedCar
attribute and modifying the availability of the car.
In the main function, we create two cars, car1 and car2, and a customer, customer. We book
car1 for the customer using the bookCar method and check the availability of car1 using the
isAvailable method. We also check the booked car of the customer using the getBookedCar
method. Then, we release the car using the releaseCar method and again check the availability
of car1.

Dr TABUEU FOTSO Laurent Cabrel


Exercise 5: Hotel Booking
Class: Hotel
Attributes:
• id (int): the unique identifier of the hotel
• name (string): the name of the hotel
• address (string): the address of the hotel
• availableRooms (int): the number of available rooms in the hotel
Methods:
• Constructor: initializes the attributes of the hotel
• Getters and setters: to access and modify the attributes of the hotel
• BookRoom(): books a room in the hotel by reducing the availableRooms count
• ReleaseRoom(): releases a room in the hotel by increasing the availableRooms count
Class: Guest
Attributes:
• id (int): the unique identifier of the guest
• name (string): the name of the guest
• bookedHotel (Hotel): the hotel booked by the guest
Methods:
• Constructor: initializes the attributes of the guest
• Getters and setters: to access and modify the attributes of the guest
• BookHotel(hotel: Hotel): books a hotel for the guest by assigning it to the bookedHotel
attribute
• ReleaseHotel(): releases the hotel booked by the guest by setting the bookedHotel attribute
to null
Association: The Guest class is associated with the Hotel class, as it contains a bookedHotel object
of the Hotel class.

C++ implementation of the classes Hotel and Guest based on the provided
specifications:
cpp
#include <iostream>
#include <string>

using namespace std;

// Hotel class
class Hotel {
private:
int id;
string name;
string address;

Dr TABUEU FOTSO Laurent Cabrel


int availableRooms;

public:
Hotel(int id, string name, string address, int availableRooms) {
this->id = id;
this->name = name;
this->address = address;
this->availableRooms = availableRooms;
}

int getId() {
return id;
}

string getName() {
return name;
}

string getAddress() {
return address;
}

int getAvailableRooms() {
return availableRooms;
}

void setName(string newName) {


name = newName;
}

void setAddress(string newAddress) {


address = newAddress;
}

void bookRoom() {
if (availableRooms > 0) {
availableRooms--;
} else {
cout << "No available rooms in the hotel." << endl;
}
}

void releaseRoom() {
availableRooms++;
}
};

// Guest class
class Guest {
private:
int id;
string name;
Hotel* bookedHotel;

public:
Guest(int id, string name) {
this->id = id;
this->name = name;
this->bookedHotel = nullptr;
}

Dr TABUEU FOTSO Laurent Cabrel


int getId() {
return id;
}

string getName() {
return name;
}

Hotel* getBookedHotel() {
return bookedHotel;
}

void setName(string newName) {


name = newName;
}

void bookHotel(Hotel* hotel) {


bookedHotel = hotel;
hotel->bookRoom();
}

void releaseHotel() {
if (bookedHotel != nullptr) {
bookedHotel->releaseRoom();
bookedHotel = nullptr;
}
}
};

int main() {
// Creating hotels
Hotel hotel1(1, "Hotel A", "123 Main Street", 10);
Hotel hotel2(2, "Hotel B", "456 Elm Street", 5);

// Creating a guest
Guest guest(1, "Alice");

// Booking a hotel for the guest


guest.bookHotel(&hotel1);

// Checking the available rooms in the hotel


cout << "Available rooms in Hotel 1: " << hotel1.getAvailableRooms() <<
endl;

// Checking the booked hotel of the guest


cout << "Guest's booked hotel: ";
if (guest.getBookedHotel() != nullptr) {
cout << guest.getBookedHotel()->getName() << endl;
} else {
cout << "None" << endl;
}

// Releasing the hotel


guest.releaseHotel();

// Checking the available rooms in the hotel after releasing


cout << "Available rooms in Hotel 1 after releasing: " <<
hotel1.getAvailableRooms() << endl;

return 0;
}

Dr TABUEU FOTSO Laurent Cabrel


In this implementation, we have defined the Hotel and Guest classes. The Hotel class has
attributes id, name, address, and availableRooms, along with respective getters and setters.
It also has methods to book and release a room by modifying the availableRooms attribute. The
Guest class has attributes id, name, and bookedHotel, along with respective getters and
setters. It also has methods to book and release a hotel by assigning or setting the bookedHotel
attribute and modifying the availability of rooms in the hotel.
In the main function, we create two hotels, hotel1 and hotel2, and a guest, guest. We book
hotel1 for the guest using the bookHotel method and check the available rooms in hotel1
using the getAvailableRooms method. We also check the booked hotel of the guest using the
getBookedHotel method. Then, we release the hotel using the releaseHotel method and
again check the available rooms in hotel1.

Problem 1: Manipulating lists and classes (C++)


1. Create a "Person" class with the following attributes:
◦ Name (String)
◦ Age (int)
2. Add a constructor to the "Person" class that takes name and age as parameters
and initializes the corresponding attributes.
3. Create a “PeopleGroup” class that represents a group of people. This class
should have an attribute of type "ArrayList" to store people.
4. Add an "addPerson" method to the "PeopleGroup" class that takes an instance
of the "Person" class as a parameter and adds it to the list of people.
5. Add a "showPeople" method to the "PeopleGroup" class that iterates through
the list of people and displays the name and age of each person.
6. In the "main" method of a main class, create a few instances of the "Person"
class and add them to an instance of the "PeopleGroup" class. Then call the
"showPeople" method to display the people in the group.
7. Add a "findPersonByName" method to the "PeopleGroup" class which takes a
name as a parameter and returns the first person found in the list with that name. If no
person is found, the method should return null.
8. In the "main" method, call the "findPersonByName" method with an existing name
and display the details of the person found. Repeat this step with a name that does not
exist.

Dr TABUEU FOTSO Laurent Cabrel


Problem 2 :Smart Home Control System
1. Create a “Device” class with the following attributes:
◦ Name (String)
◦ Status (boolean): represents whether the device is on or off
2. Add a constructor to the "Device" class that takes the name of the device as
parameters and initializes the state to off by default.
3. Add methods to turn the device on and off.
4. Create a “SmartHome” class that represents a house with multiple devices. This
class should have an attribute of type "ArrayList" to store the devices.
5. Add an “addDevice” method to the “SmartHome” class that takes an instance of
the “Device” class as a parameter and adds it to the list of devices.
6. Add a "showDevicesOn" method to the "SmartHome" class that iterates through
the list of devices and displays the names of the devices that are on.
7. In the "main" method of a main class, create a few instances of the "Device"
class to represent different devices in the house (e.g. a light, a heating system, a
security camera, etc.) . Add these devices to an instance of the “SmartHome” class.
Next, turn on some devices and call the "showOnDevices" method to display the
turned on devices.
8. Add a “getDeviceByName” method to the “SmartHome” class that takes a
device name as a parameter and returns the corresponding device. If no device is
found, the method should return null.
9. In the "main" method, call the "getDeviceByName" method with an existing
device name and display the status of the device found.

Problem 3 : Object-oriented programming in C++


Suppose you are developing a system for a smart city that manages different
aspects of urban life. You need to design classes to represent different elements of
this smart city.
9. “Sensor” class

Dr TABUEU FOTSO Laurent Cabrel


◦ Create a “Sensor” class that represents a sensor used to collect data in the
smart city.
◦ Add attributes to store the sensor ID, sensor type (e.g. temperature, air
pollution, sound levels, etc.), and geographic coordinates of the sensor.
◦ Add methods to access attributes and modify them as necessary.
10. “Building” class
◦ Create a “Building” class that represents a building in the smart city.
◦ Add attributes to store the building ID, building name, address, and building
function (for example, residential, commercial, government, etc.).
◦ Add methods to access attributes and modify them as necessary.
11. Class “Vehicle”
◦ Create a “Vehicle” class that represents a vehicle in the smart city.
◦ Add attributes to store the vehicle ID, vehicle type (e.g. car, bus, bicycle, etc.),
vehicle driver, and vehicle location.
◦ Add methods to access attributes and modify them as necessary.
12. Class “SmartCityManager”
◦ Create a “SmartCityManager” class which represents the smart city manager.
◦ Add attributes to store a list of sensors, a list of buildings, and a list of vehicles
present in the city.
◦ Add methods to add sensors, buildings, and vehicles to the city, as well as
display information from all sensors, buildings, and vehicles present.

Part 2 : Micro-controller and embedded


system

Exercise 1: LED Controller


Design a class called "LED" that represents an LED connected to a microcontroller.
The LED class should have member functions to turn the LED on, turn it off, and

Dr TABUEU FOTSO Laurent Cabrel


toggle its state. Additionally, include a member variable to store the current state of
the LED (on or off).
Explanation:
class LED {
private:
bool isOn; // Member variable to store the state of the LED

public:
LED() {
isOn = false; // Initialize the LED state as off
}

void turnOn() {
isOn = true; // Set the state of the LED to on
// Code to actually turn on the LED
}

void turnOff() {
isOn = false; // Set the state of the LED to off
// Code to actually turn off the LED
}

void toggle() {
isOn = !isOn; // Toggle the state of the LED
// Code to actually toggle the LED state
}
};

In this exercise, we create a class called "LED" with a private member variable isOn
to store the state of the LED (on or off). The constructor initializes the LED state as
off. The member functions turnOn(), turnOff(), and toggle() allow us to
control the LED by changing its state.
Exercise 2: Temperature Sensor
Create a class called "TemperatureSensor" that represents a temperature sensor
connected to a microcontroller. The TemperatureSensor class should have member
functions to read the temperature value and provide it in a desired unit (e.g., Celsius,
Fahrenheit). The class should also include a member variable to store the last
measured temperature value.
Explanation:
class TemperatureSensor {
private:
float lastTemperature; // Member variable to store the last measured
temperature

public:
TemperatureSensor() {
// Initialize the lastTemperature variable
lastTemperature = 0.0;

Dr TABUEU FOTSO Laurent Cabrel


}

float readTemperature() {
// Code to read the temperature from the sensor
// Store the measured temperature in lastTemperature variable
lastTemperature = 25.5; // Example value, replace with actual sensor
reading
return lastTemperature;
}

float getTemperatureInCelsius() {
return lastTemperature; // Return the temperature in Celsius
}

float getTemperatureInFahrenheit() {
return (lastTemperature * 9/5) + 32; // Convert and return the
temperature in Fahrenheit
}
};

In this exercise, we create a class called "TemperatureSensor" with a private member


variable lastTemperature to store the last measured temperature. The
constructor initializes the lastTemperature variable. The member function
readTemperature() simulates reading the temperature from the sensor and
updates the lastTemperature variable. The member functions
getTemperatureInCelsius() and getTemperatureInFahrenheit()
provide the temperature in Celsius and Fahrenheit, respectively, based on the last
measured value.
Exercise 3: Motor Controller
Design a class called "Motor" that represents a motor connected to a microcontroller.
The Motor class should have member functions to control the motor's speed and
direction. Additionally, include member variables to store the current speed and
direction of the motor.
Explanation:
class Motor {
private:
int speed; // Member variable to store the speed of the motor
bool isClockwise; // Member variable to store the direction of the motor

public:
Motor() {
// Initialize the speed and direction variables
speed = 0;
isClockwise = true; // Assume clockwise as the default direction
}

void setSpeed(int newSpeed) {


speed = newSpeed; // Set the speed of the motor
// Code to actually set the motor speed

Dr TABUEU FOTSO Laurent Cabrel


}

void setDirection(bool clockwise) {


isClockwise = clockwise; // Set the direction of the motor
// Code to actually set the motor direction
}

void start() {
// Code to start the motor
}

void stop() {
// Code to stop the motor
}
};

In this exercise, we create a class called "Motor" with private member variables
speed and isClockwise to store the speed and direction of the motor,
respectively. The constructor initializes the speed and direction variables. The
member functions setSpeed() and setDirection() allow us to change the
speed and direction of the motor. The member functions start() and stop()
simulate starting and stopping the motor, respectively.
Exercise 4: Communication Protocol
Create a base class called "CommunicationProtocol" that defines the common
interface for different communication protocols (e.g., UART, SPI, I2C). Derived
classesI apologize for the incomplete response. Here's the continuation of the
previous explanation:
Exercise 4: Communication Protocol (continued)
Create a base class called "CommunicationProtocol" that defines the common
interface for different communication protocols (e.g., UART, SPI, I2C). Derived
classes should implement specific functionalities for each protocol. For example, the
UART class could have member functions to send and receive data using UART
communication.
Explanation:
class CommunicationProtocol {
public:
virtual void sendData(const char* data, int length) = 0;
virtual void receiveData(char* buffer, int length) = 0;
// Other common communication functions can be added here
};

class UART : public CommunicationProtocol {


public:
void sendData(const char* data, int length) override {
// Code to send data using UART
}

Dr TABUEU FOTSO Laurent Cabrel


void receiveData(char* buffer, int length) override {
// Code to receive data using UART
}
// Any additional UART-specific functions can be added here
};

In this exercise, we create a base class called "CommunicationProtocol" with pure


virtual functions sendData() and receiveData(). These functions define the
common interface for different communication protocols. The sendData()
function takes a character array and its length as parameters to send data, while the
receiveData() function receives data into a buffer specified by a character array
and its length.
We then create a derived class called "UART" that inherits from the base class
"CommunicationProtocol." The derived class overrides the sendData() and
receiveData() functions to implement the specific functionality of UART
communication.
Exercise 5: Alarm System
Design a class called "AlarmSystem" that represents an alarm system connected to a
microcontroller. The AlarmSystem class should have member functions to arm and
disarm the alarm, trigger the alarm, and provide status information. Additionally,
include member variables to store the current alarm status (armed, disarmed,
triggered).
Explanation:
class AlarmSystem {
private:
enum AlarmStatus { ARMED, DISARMED, TRIGGERED };
AlarmStatus currentStatus; // Member variable to store the current alarm
status

public:
AlarmSystem() {
currentStatus = DISARMED; // Initialize the alarm status as disarmed
}

void armAlarm() {
currentStatus = ARMED; // Set the alarm status as armed
// Code to activate the alarm system
}

void disarmAlarm() {
currentStatus = DISARMED; // Set the alarm status as disarmed
// Code to deactivate the alarm system
}

void triggerAlarm() {
currentStatus = TRIGGERED; // Set the alarm status as triggered

Dr TABUEU FOTSO Laurent Cabrel


// Code to trigger the alarm
}

AlarmStatus getStatus() const {


return currentStatus; // Return the current alarm status
}
};

In this exercise, we create a class called "AlarmSystem" with a private member


variable currentStatus of the enum type AlarmStatus. The enum
AlarmStatus defines three possible values: ARMED, DISARMED, and
TRIGGERED. The constructor initializes the alarm status as disarmed. The member
functions armAlarm(), disarmAlarm(), and triggerAlarm() allow us to
change the alarm status accordingly. The getStatus() function returns the current
alarm status.

Exercise : Traffic Light Controller


Design an embedded system program to control a traffic light intersection. The
system should have inputs for detecting vehicle presence and outputs to control the
traffic lights. Implement the logic to switch the lights based on predefined timing
patterns (e.g., green for 30 seconds, yellow for 5 seconds, red for 30 seconds).
Explanation:
In this exercise, we are designing an embedded system for a traffic light controller.
The system requires inputs to detect vehicle presence at each intersection and outputs
to control the traffic lights. The embedded system needs to implement the logic to
switch the lights based on a predefined timing pattern.
To accomplish this, we can write a program that continuously monitors the vehicle
presence inputs and updates the traffic light outputs accordingly. We can use timers or
counters to keep track of the elapsed time for each light state.
For example, let's assume we have three lights: red, yellow, and green. We can use
variables to represent the current state of each light. Here's a simplified pseudocode
representation:
bool isVehiclePresent = false;
int greenTime = 30; // Time in seconds
int yellowTime = 5; // Time in seconds
int redTime = 30; // Time in seconds

void trafficLightController() {
while (true) {
if (isVehiclePresent) {

Dr TABUEU FOTSO Laurent Cabrel


// Activate green light for greenTime seconds
activateGreenLight();
delay(greenTime);

// Activate yellow light for yellowTime seconds


activateYellowLight();
delay(yellowTime);

// Activate red light for redTime seconds


activateRedLight();
delay(redTime);
} else {
// No vehicles detected, keep red light active
activateRedLight();
delay(1); // Delay for 1 second before checking again
}
}
}

In this example, the while loop continuously checks the input for vehicle presence. If
a vehicle is present, the program activates the green light for the specified greenTime,
followed by the yellow light for the specified yellowTime, and finally the red light
for the specified redTime. If no vehicles are detected, the program keeps the red light
active.
Exercise : Temperature and Humidity Monitor
Design an embedded system program to monitor temperature and humidity using a
sensor. The system should periodically read the sensor data, display it on an LCD
screen, and sound an alarm if the temperature or humidity exceeds certain thresholds.
Explanation:
For this exercise, we will design an embedded system program to monitor
temperature and humidity using a sensor. The system should periodically read the
sensor data, display it on an LCD screen, and trigger an alarm if the temperature or
humidity exceeds predefined thresholds.
Here's a simplified pseudocode representation:
float temperatureThreshold = 25.0; // Temperature threshold in degrees Celsius
float humidityThreshold = 70.0; // Humidity threshold in percentage
float currentTemperature;
float currentHumidity;

void temperatureHumidityMonitor() {
while (true) {
// Read temperature and humidity from the sensor
currentTemperature = readTemperature();
currentHumidity = readHumidity();

// Display temperature and humidity on the LCD screen


displayOnLCD("Temperature: " + currentTemperature + "C");
displayOnLCD("Humidity: " + currentHumidity + "%");

Dr TABUEU FOTSO Laurent Cabrel


// Check if temperature or humidity exceeds thresholds
if (currentTemperature > temperatureThreshold || currentHumidity >
humidityThreshold) {
activateAlarm(); // Trigger the alarm
}

delay(1000); // Delay for 1 second before reading again


}
}

In this example, the while loop continuously reads the temperature and humidity
values from the sensor. It then displays the readings on an LCD screen. The program
checks if the current temperature or humidity exceeds the predefined thresholds. If
either exceeds the thresholds, the program activates an alarm.
These exercises should give you a good starting point to apply the concepts of
embedded systems.

C++ Object-Oriented Programming:


Exercises, Practices

1. Write a C++ program to implement a class called Circle that has private
member variables for radius. Include member functions to calculate the circle's
area and circumference.

#include <iostream>

Dr TABUEU FOTSO Laurent Cabrel


#include <cmath>

const double PI = 3.14159;

class Circle {
private: double radius;

public:
// Constructor
Circle(double rad): radius(rad) {}

// Member function to calculate the area


double calculateArea() {
return PI * pow(radius, 2);
}

// Member function to calculate the circumference


double calculateCircumference() {
return 2 * PI * radius;
}
};

int main() {
// Create a circle object
double radius;
std::cout << "Input the radius of the circle: ";
std::cin >> radius;
Circle circle(radius);

// Calculate and display the area


double area = circle.calculateArea();

Dr TABUEU FOTSO Laurent Cabrel


std::cout << "Area: " << area << std::endl;

// Calculate and display the circumference


double circumference = circle.calculateCircumference();
std::cout << "Circumference: " << circumference << std::endl;

return 0;
}

2. Write a C++ program to create a class called Rectangle that has private
member variables for length and width. Implement member functions to
calculate the rectangle's area and perimeter.
#include <iostream>
class Rectangle {
private: double length;
double width;

public:
// Constructor
Rectangle(double len, double wid): length(len),
width(wid) {}

// Member function to calculate the area


double calculateArea() {
return length * width;
}

// Member function to calculate the perimeter

Dr TABUEU FOTSO Laurent Cabrel


double calculatePerimeter() {
return 2 * (length + width);
}
};

int main() {

double length, width;


std::cout << "Input the length of the rectangler: ";
std::cin >> length;
std::cout << "Input the width of the rectangle: ";
std::cin >> width;

// Create a rectangle object


Rectangle rectangle(length, width);

// Calculate and display the area


double area = rectangle.calculateArea();
std::cout << "\nArea: " << area << std::endl;

// Calculate and display the perimeter


double perimeter = rectangle.calculatePerimeter();
std::cout << "Perimeter: " << perimeter << std::endl;

return 0;
}

Dr TABUEU FOTSO Laurent Cabrel


3. Write a C++ program to create a class called Person that has private member
variables for name, age and country. Implement member functions to set and
get the values of these variables.
#include <iostream>

#include <string>

class Person {
private: std::string name;
int age;
std::string country;

public:
// Setter functions
void setName(const std::string & n) {
name = n;
}

void setAge(int a) {
age = a;
}

void setCountry(const std::string & c) {


country = c;
}

// Getter functions

Dr TABUEU FOTSO Laurent Cabrel


std::string getName() {
return name;
}

int getAge() {
return age;
}

std::string getCountry() {
return country;
}
};

int main() {
// Create a person object
Person person;

// Set the person's details


person.setName("Saveli Sujatha");
person.setAge(25);
person.setCountry("USA");

// Get and display the person's details


std::cout << "Name: " << person.getName() << std::endl;
std::cout << "Age: " << person.getAge() << std::endl;
std::cout << "Country: " << person.getCountry() << std::endl;

Dr TABUEU FOTSO Laurent Cabrel


return 0;
}

4. Write a C++ program to create a class called Car that has private member
variables for company, model, and year. Implement member functions to get
and set these variables.

#include <iostream>
#include <string>

class Car {
private: std::string company;
std::string model;
int year;

public:
// Constructor
Car(const std::string & comp,
const std::string & mdl, int yr): company(comp),
model(mdl),
year(yr) {}

// Getter functions
std::string getCompany() {
return company;
}

std::string getModel() {
return model;

Dr TABUEU FOTSO Laurent Cabrel


}

int getYear() {
return year;
}

// Setter functions
void setCompany(const std::string & comp) {
company = comp;
}

void setModel(const std::string & mdl) {


model = mdl;
}

void setYear(int yr) {


year = yr;
}
};

int main() {
// Create a car object
Car car("AUDI", "A6", 2023);

// Get and display the car details


std::cout << "Company: " << car.getCompany() << std::endl;
std::cout << "Model: " << car.getModel() << std::endl;
std::cout << "Year: " << car.getYear() << std::endl;

Dr TABUEU FOTSO Laurent Cabrel


// Set new values for the car
car.setCompany("BMW");
car.setModel("M4");
car.setYear(2022);

// Get and display the updated car details


std::cout << "\nUpdated Company: " << car.getCompany() << std::endl;
std::cout << "Updated Model: " << car.getModel() << std::endl;
std::cout << "Updated Year: " << car.getYear() << std::endl;

return 0;
}

5. Write a C++ program to implement a class called BankAccount that has


private member variables for account number and balance. Include member
functions to deposit and withdraw money from the account.
#include <iostream>
#include <string>
class BankAccount {
private: std::string accountNumber;
double balance;

public:
// Constructor
BankAccount(const std::string & accNum, double initialBalance): accountNumber(accNum),
balance(initialBalance) {}

// Member function to deposit money


void deposit(double amount) {
balance += amount;

Dr TABUEU FOTSO Laurent Cabrel


std::cout << "Deposit successful. Current balance: " << balance << std::endl;
}

// Member function to withdraw money


void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
std::cout << "Withdrawal successful. Current balance: " << balance << std::endl;
} else {
std::cout << "Insufficient balance. Cannot withdraw." << std::endl;
}
}
};

int main() {
// Create a bank account object
std::string sacno = "SB-123";
double Opening_balance, deposit_amt, withdrawal_amt;
Opening_balance = 1000;
std::cout << "A/c. No." << sacno << " Balance: " << Opening_balance << std::endl;

BankAccount account(sacno, 1000.0);

// Deposit money into the account


deposit_amt = 1500;
std::cout << "Deposit Amount: " << deposit_amt << std::endl;
account.deposit(deposit_amt);

// Withdraw money from the account


withdrawal_amt = 750;
std::cout << "Withdrawl Amount: " << withdrawal_amt << std::endl;

Dr TABUEU FOTSO Laurent Cabrel


account.withdraw(withdrawal_amt);

// Attempt to withdraw more money than the balance


withdrawal_amt = 1800;
std::cout << "Attempt to withdrawl Amount: " << withdrawal_amt << std::endl;
account.withdraw(withdrawal_amt);

return 0;
}

6. Write a C++ program to create a class called Triangle that has private
member variables for the lengths of its three sides. Implement member
functions to determine if the triangle is equilateral, isosceles, or scalene.

7. Write a C++ program to implement a class called Employee that has private
member variables for name, employee ID, and salary. Include member
functions to calculate and set salary based on employee performance.

8. Write a C++ program to implement a class called Date that has private
member variables for day, month, and year. Include member functions to set
and get these variables, as well as to validate if the date is valid.

9. Write a C++ program to implement a class called Student that has private
member variables for name, class, roll number, and marks. Include member
functions to calculate the grade based on the marks and display the student's
information.

10. Write a C++ program to implement a class called Shape with virtual
member functions for calculating area and perimeter. Derive classes such as
Circle, Rectangle, and Triangle from the Shape class and override virtual
functions accordingly.

Dr TABUEU FOTSO Laurent Cabrel

You might also like