Wa0029.
Wa0029.
Q. Do as directed:
1. Define operator overloading in C++. Provide two examples of operators that can be overloaded.
2. List and describe at least five operators that can be overloaded. Are there any operators that cannot
be overloaded?
3. Write the general syntax for overloading an operator as a member function.
MCQs
1. What is the primary purpose of operator overloading in C++?
A) To increase execution speed B) To enable the use of operators with user-defined types
C) To define new operators D) To simplify memory management
2. What is the return type of an overloaded operator function typically?
A) It must be void B) It must be a pointer C) It can be any type D) It must be an integer
3. When an object is passed to a function by value, what happens?
A) A reference to the original object is passed. B) The function cannot access the object.
C) The original object is modified. D) A copy of the object is created and passed.
4. If you pass an object to a function by reference and modify it within that function, what happens?
A) The original object remains unchanged. B) The original object is modified.
C) A copy of the object is modified. D) It results in a compilation error.
Program
Modify the time class program, so that instead of a function add_time() it uses the overloaded +
operator to add two times. Write a program to test this class.
class time {
private:
int hrs, mins, secs;
public:
time() {
hrs = mins = secs = 0; }
time(int h, int m, int s) {
hrs = h;
mins = m;
secs = s; }
void display() {
cout << hrs << “:” << mins << “:” << secs; }
void add_time(time t1, time t2) {
hrs = t1.hrs + t2.hrs;
mins = t1.mins + t2.mins;
secs = t1.secs + t2.secs; }
};
main() {
time time1(5, 59, 59);
time time2(4, 30, 30);
time time3;
time3.add_time(time1, time2);
cout << “time3 = “;
time3.display();
}