Overloading In C++ Mcq Exercise 3

  1. What is the best way to declare a friend function to overload the binary + operator in C ++?
  2. Example
    
    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.

  1. 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.

  1. 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.

  1. Which of the following syntax overloads the unary minus (-) operator for a class?
  2. Example
    
    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.

  1. What is the return type of the overloaded subscript operator in a class for read-only access?
  2. Example
    
    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.

  1. 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.

Input Required

This code uses input(). Please provide values below: