Operator Overloading - Viva Q&A Summary
1. Fundamentals of Operator Overloading
Q: What is operator overloading?
A: Operator overloading is a feature in C++ that allows you to redefine the behavior of an operator for user-defined types
(e.g., classes).
Q: Can all operators be overloaded?
A: No. Certain operators like ::, ., .*, sizeof, and ?: cannot be overloaded.
Q: Why do we use operator overloading?
A: To make code involving objects more intuitive and readable by using standard operators (like +, -) with objects.
2. Restrictions on Operator Overloading
Q: Can we overload the sizeof operator?
A: No, the sizeof operator cannot be overloaded.
Q: Why can't we change operator precedence during overloading?
A: Operator precedence and associativity are defined by the C++ language and cannot be changed to maintain
consistency and avoid confusion.
3. Operator Functions as Class Members vs. Friend Functions
Q: What's the difference between member and friend operator functions?
A: - Member functions use the invoking object as the left operand.
- Friend functions are non-members and take both operands as arguments.
Q: When would you prefer a friend function?
A: When the left operand is not an object of the class or when external access to private members is needed.
4. Overloading Unary Operators
Q: What is a unary operator?
A: An operator that works with a single operand, like ++, --, -, !.
Q: How do you overload ++ or --?
A: By defining a function with the syntax:
ReturnType operator++(); // Prefix
ReturnType operator++(int); // Postfix
5. Overloading Binary Operators
Q: What is the syntax to overload binary operators?
A: ReturnType operator+(const ClassName& obj); // Member
Operator Overloading - Viva Q&A Summary
friend ReturnType operator+(ClassName, ClassName); // Friend
Q: Can binary operators be overloaded with friend functions?
A: Yes, especially when the left operand is not a class object or to access private members of both objects.
6. Overloading Using Friend Functions
Q: What is a friend function?
A: A non-member function that has access to the private and protected members of a class by declaring it with the friend
keyword.
Q: What are the advantages of using friend functions for overloading?
A: - Access to private members of multiple objects.
- Needed when left operand is not a class object.
- Keeps the class interface clean.