CPP Operator Overloading & Type Conversions 1 — Questions and Answers
Question 1: Which keyword is used to define an overloaded operator in C++?
- function
- override
- operator (Correct answer)
- overload
Correct answer: operator
The `operator` keyword followed by the operator symbol (e.g., `operator+`) defines an overloaded operator in C++.
Question 2: Which of the following operators CANNOT be overloaded in C++?
- operator+
- operator[]
- operator:: (Correct answer)
- operator->
Correct answer: operator::
The scope resolution operator (::), dot operator (.), sizeof, typeid, and ternary (?:) cannot be overloaded.
Question 3: What is the conventional return type for the copy assignment operator (operator=)?
- void
- bool
- T& (Correct answer)
- const T&
Correct answer: T&
The assignment operator should return `T&` (reference to *this) to support chaining such as `a = b = c`.
Question 4: How is the postfix increment operator (++) differentiated from the prefix version when overloading?
- Postfix takes a dummy int parameter (Correct answer)
- Postfix returns a reference to *this
- Prefix takes a dummy int parameter
- Postfix must be declared static
Correct answer: Postfix takes a dummy int parameter
The postfix version is declared as `operator++(int)` with a dummy int parameter to distinguish it from the prefix `operator++()`.
Question 5: Which of the following operators MUST be overloaded as a member function?
- operator+
- operator<<
- operator= (Correct answer)
- operator==
Correct answer: operator=
The assignment (=), subscript ([]), call (()), and arrow (->) operators must be defined as member functions per the C++ standard.
Question 6: What does the `explicit` keyword do when applied to a single-argument constructor?
- Makes the constructor virtual
- Prevents implicit conversions using that constructor (Correct answer)
- Forces the constructor to be inlined
- Makes the constructor private
Correct answer: Prevents implicit conversions using that constructor
`explicit` prevents the compiler from using that constructor for implicit type conversions, requiring an explicit cast instead.
Question 7: When overloading the output stream operator (operator<<), what should be the first parameter type?
- const MyClass&
- std::ostream
- std::ostream& (Correct answer)
- MyClass&
Correct answer: std::ostream&
The first parameter must be `std::ostream&` (a non-const reference) so the stream state can be updated and chaining with << is supported.
Which keyword is used to define an overloaded operator in C++?