TP oop with c++
TP oop with c++
" 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;
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"
friendCar.color = "Blue";
friendCar.brand = "Ford";
friendCar.model = "Mustang";
friendCar.start();
friendCar.accelerate();
friendCar.stop();
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.
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;
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().
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;
}
int getId() {
return id;
}
string getName() {
return name;
}
double getPrice() {
return price;
}
class Cart {
private:
vector<Product> products;
public:
void addToCart(Product product) {
products.push_back(product);
}
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;
}
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);
return 0;
}
C++ implementation of the classes User, Message, and Chat based on the provided
specifications:
cpp
#include <iostream>
#include <vector>
#include <string>
#include <ctime>
// User class
class User {
private:
int id;
string username;
public:
User(int id, string username) {
int getId() {
return id;
}
string getUsername() {
return username;
}
// 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;
public:
Chat(int id) {
this->id = id;
}
int main() {
// Creating users
User user1(1, "Alice");
User user2(2, "Bob");
// Creating a chat
Chat chat(1);
// Sending a message
chat.sendMessage(user1, user2, "Hello, how are you?");
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.
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>
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;
}
// Student class
class Student {
private:
int id;
string name;
vector<Course> courses;
public:
Student(int id, string name) {
this->id = id;
this->name = name;
int getId() {
return id;
}
string getName() {
return name;
}
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");
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.
C++ implementation of the classes Car and Customer based on the provided specifications:
cpp
#include <iostream>
#include <string>
// 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 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 releaseCar() {
int main() {
// Creating cars
Car car1(1, "Toyota", "Camry");
Car car2(2, "Honda", "Civic");
// Creating a customer
Customer customer(1, "Alice", "1234567890");
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.
C++ implementation of the classes Hotel and Guest based on the provided
specifications:
cpp
#include <iostream>
#include <string>
// Hotel class
class Hotel {
private:
int id;
string name;
string address;
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 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;
}
string getName() {
return name;
}
Hotel* getBookedHotel() {
return bookedHotel;
}
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");
return 0;
}
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;
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
}
};
public:
Motor() {
// Initialize the speed and direction variables
speed = 0;
isClockwise = true; // Assume clockwise as the default 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
};
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
void trafficLightController() {
while (true) {
if (isVehiclePresent) {
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();
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.
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>
class Circle {
private: double radius;
public:
// Constructor
Circle(double rad): radius(rad) {}
int main() {
// Create a circle object
double radius;
std::cout << "Input the radius of the circle: ";
std::cin >> radius;
Circle circle(radius);
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) {}
int main() {
return 0;
}
#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;
}
// Getter functions
int getAge() {
return age;
}
std::string getCountry() {
return country;
}
};
int main() {
// Create a person object
Person person;
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;
int getYear() {
return year;
}
// Setter functions
void setCompany(const std::string & comp) {
company = comp;
}
int main() {
// Create a car object
Car car("AUDI", "A6", 2023);
return 0;
}
public:
// Constructor
BankAccount(const std::string & accNum, double initialBalance): accountNumber(accNum),
balance(initialBalance) {}
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;
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.