Skip to main content

Important Introduction to Programming Short Questions

Chapter: 32
Question 1:
How can the addition of an integer to a Date object (e.g., 5 + date) be implemented?
Answer: This requires defining a friend function that takes an integer and a Date object, adding the integer to the Date, and returning a new Date object. It cannot be a member function because the integer is not part of the Date class.
Chapter: 32
Question 2:
What role do friend functions play in operator overloading?
Answer: Friend functions allow operators to be defined for cases where the left-hand operand is not a member of the class, such as integer + Date. They can access private members of the class, enabling more flexible and powerful operations.
Chapter: 33
Question 3:
What is the purpose of operator overloading in classes?
Answer: Operator overloading allows custom behavior for operators when applied to objects of user-defined classes, making code more intuitive and clean.
Chapter: 33
Question 4:
How does the default assignment operator work in C++?
Answer: The default assignment operator performs a member-wise copy of data members from one object to another.
Chapter: 33
Question 5:
Why is a custom assignment operator needed for a class with dynamic memory?
Answer: A custom assignment operator is needed to properly handle memory allocation and avoid issues like double deletion or memory leaks when objects are assigned to each other.
Chapter: 33
Question 6:
How should a custom assignment operator handle self-assignment?
Answer: It should check if the object being assigned is the same as the object being assigned to, and if so, do nothing to avoid invalid memory operations.
Chapter: 33
Question 7:
What is the role of the this pointer in a class member function?
Answer: The this pointer refers to the calling object, allowing access to its members and distinguishing between different object instances.
Chapter: 33
Question 8:
How does the this pointer help in chaining assignment operations?
Answer: The this pointer allows the assignment operator to return a reference to the calling object, enabling chained assignments like s3 = s2 = s1;.
Chapter: 33
Question 9:
What is self-assignment and why is it problematic in memory management?
Answer: Self-assignment occurs when an object is assigned to itself, potentially leading to issues like freeing the same memory twice. It requires special handling in the assignment operator.
Chapter: 33
Question 10:
How can you avoid issues with self-assignment in a custom assignment operator?
Answer: By checking if the this pointer is equal to the address of the object being assigned, and returning early if they are the same.