- What method is recommended for declaring a friend function to override the binary + operator in C++?
class A {
int value;
public:
A(int v) : value(v) {}
friend A operator+(const A&, const A&);
};
- A operator+(A, A);
- A operator+(const A&, const A&);
- A operator+(A&);
- A operator+(const A&);
Explanation:
The correct answer is option (b). The friend function to overload the binary + operator should be declared with two parameters, both passed by constant reference.
- Which keyword is used to overload an operator as a non-member function but still access private members?
- static
- friend
- virtual
- inline
Explanation:
The correct answer is option (a). The friend keyword permits a non-member function to access private members of a class for operator overloading.
- Can the new and delete operators be overloaded in C++?
- Both
- None of the above
Explanation:
The accurate choice is alternative (a). Within the C++ programming language, it is possible to overload the new and delete operators to manage memory allocation and deallocation.
- Which of the subsequent syntax options overloads the unary minus (-) operator for a class?
class A {
public:
A operator-() const;
};
- A operator-(int);
- A operator-;
- A operator- const;
- A operator- &;
Explanation:
The accurate choice is alternative (c). The unary negative operator - is redefined as a constant member function without any arguments.
- What return type does the overridden subscript operator have in a class designed for read-only access?
class A {
public:
const int& operator[](size_t index) const;
};
- int&
- const int&
- int*
Explanation:
The correct answer is option (c). Since the subscript operator has read-only access, it must return a constant reference for the element type.
- Which of the following statements about function call operator overloading is correct?
- It cannot be overloaded.
- It must be a friend function.
- It allows objects to be used as functions.
- It can only be overloaded in derived classes.
Explanation:
The appropriate choice is alternative (c). The call function operator can be overloaded to enable objects to be invoked as if they were functions.