Exercise 1: Rectangle Class With Methods and Properties
Practice Problem: Define a class Rectangle with private members int
length and int width. Implement a constructor to set the dimensions. Implement
two public methods: calculate_area() which returns the product of length and
width, and calculate_perimeter() which returns 2 * (length + width).
Expected Output:
Dimensions: 10x5
Area: 50
Perimeter: 30
Exercise 5: Default/Parameterized Constructor
Practice Problem: Implement the Rectangle class (from Exercise 1). This time,
include two public constructors: a default constructor that sets
both length and width to 1, and a parameterized constructor that allows setting
custom values for length and width.
Expected Output:
Custom Rectangle created (12x4).
R1 Area: 48
Default Rectangle created (1x1).
R2 Area: 1
Practice Problem: Create a class Point with a private member int x and int y as a
coordinates. Implement a copy constructor for this class. Write
a display() method. Demonstrate its use by creating a new Point object as a
copy of an existing one.
Given:
class Point {
private:
int x;
int y;
};
Expected Output:
Point(10, 20)
Copy Constructor called.
Point(10, 20)
After moving p2:
Point(10, 20)
Point(15, 25)
Practice Problem: Overload the binary addition operator (+) for the Point class
(with private members x and y coordinates). The overloaded operator should
take two Point objects as operands and return a new Point object that represents
the component-wise sum: (x1, y1) + (x2, y2) = (x1+x2, y1+y2).
Given:
class Point {
private:
int x;
int y;
};
Expected Output:
P1: (10, 5)
P2: (3, 7)
P3 (P1 + P2): (13, 12)
Practice Problem: Create a Car class with public attributes std::string
make, std::string model, and int year. Implement a public
method start_engine() that simply prints the message: “[Year] [Make] [Model]
engine started!”.
Expected Output:
2020 Toyota Corolla engine started!
Exercise 8: Date Class with Validation
Practice Problem: Create a Date class with private members int day, int month,
and int year. Implement a constructor that performs basic validation: if the
month is not between 1 and 12, it should set the month to a default value (e.g.,
1) and print an error message.
Expected Output:
Date 1: 2025-10-28
Valid Date: 2025-10-28
Date 2: 2025-13-1
Warning: Invalid month (13) provided. Setting to 1.
Valid Date: 2025-1-1
Exercise 11: Temperature Converter With Getters and Setters
Practice Problem: Implement a class Temperature with a private
member double celsius. Provide a public setter method set_celsius(double c) to
assign a value to the private member. Also, provide a
public getter method get_fahrenheit() that calculates and returns the
temperature in Fahrenheit using the formula: F = C (9/5) + 32.
Given:
class Temperature {
private:
double celsius;
};
Expected Output:
Celsius set to: 25
Fahrenheit: 77
Celsius set to: 100
Fahrenheit: 212