- What is the best way to declare a friend function to overload 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 correct answer is option (a). In C++, the new and delete operators can be overloaded to access memory allocation and deallocation.
- Which of the following syntax 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 correct answer is option (c). The unary minus operator - is overloaded as a const member function with no parameters.
- What is the return type of the overloaded subscript operator in a class 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 correct answer is option (c). The function call operator can be overloaded to allow objects to be used because they are also functions.