Mastering C++: A Comprehensive Quiz Based on 'Thinking in C++'

Disable ads (and more) with a membership for a one time $2.99 payment

Test your C++ skills with our quiz based on Bruce Eckel's 'Thinking in C++'. Dive into object-oriented programming, advanced topics, and fundamentals. Perfect for learners and experts alike. Assess your knowledge and become a C++ master!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


For a class 'Integer', what is the correct definition for overloading the unary '-' operator as a global function?

  1. Integer operator-(const Integer&);

  2. const Integer operator-(const Integer&);

  3. const Integer& operator-(const Integer& a);

  4. Integer& operator-(Integer a);

The correct answer is: const Integer operator-(const Integer&);

The options A, C, and D are incorrect because they do not specify that the return type should be a constant Integer object. In order to correctly overload the unary '-' operator as a global function for the 'Integer' class, the return type must be explicitly declared as const Integer. This allows for the returned value to be used in expressions without causing any unintended changes to the original object. Additionally, option D is incorrect because it should not take in an Integer object as a parameter, since the operator is being overloaded as a global function and not a member function. Overall, option B is the best choice for correctly defining the unary '-' operator as a global function for the 'Integer' class.