- Which of the following statements, which would be the scope of friend function in C++?
- Class scope
- Global scope
- Protected scope
- Local
Explanation:
The correct answer is option (b). The friend functions in the c++ will have the global scope since they are not the members of the class.
- Can a friend function be declared as const?
- Both
- None
Explanation:
The correct answer is option (b). The const variable cannot be used when declaring friend functions because the functions are not member functions of a class and do not apply to any instance of the class.
- What is the output for the below following C++ code?
#include<iostream>
using namespace std;
class A
{
int x;
public:
A(int val) : x(val) {}
friend void operator++(A &a);
};
void operator++(A &a)
{
a.x++;
cout << a.x;
}
int main()
{
A obj(10);
++obj;
return 0;
}
- Runtime error
Explanation:
The correct answer is option (b). The friend function operator (++) overloads the increment operator to increment the private member x of class A and prints the result, which is 11.
- What is the output for the below following C++ Code?
#include<iostream>
using namespace std;
class A
{
int x;
public:
A() : x(5) {}
friend void increase(A &a);
void display() const {
cout << x;
}
};
void increase(A &a)
{
a.x += 10;
}
int main()
{
A obj;
increase(obj);
obj.display();
return 0;
}
- Runtime error
Explanation:
The correct answer is option (c). The friend function increase modifies the private member x of class A, and the display member function prints the updated value, which is 15.
- Whether the below following syntax is the correct way of declaring the friend function for class A?
class A {
public:
void friend display();
};
- Correct
- Incorrect
- None of the above
- Both a and b
Explanation:
The correct answer is option (b). In the correct way of declaring friend function, void keyword is not included before friend.
- Is it possible to call a friend function using object of a class?
- Both
- None
Explanation:
The correct answer is option (b). A friend function is not a member of the class, so it cannot be called using an object of the class. It must be called independently.