- 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 answer you should choose is alternative (b). Friend functions cannot be declared using the const qualifier since they are not part of a class as member functions and do not act on any specific class instance.
- What will be the result when executing the provided 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 accurate choice is alternative (b). The friend function operator (++) is used to overload the increment operator for increasing the private member x within class A and displaying the resulting value, which is 11.
- What will be the result of the 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 accurate choice is alternative (c). The friend function increase alters the private member x within class A, while the display member function showcases the adjusted value, which is 15.
- Is the syntax provided below the appropriate method to declare a 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 accurate choice is alternative (b). A friend function stands outside the class scope, hence it is unable to be invoked through a class object. It necessitates an independent invocation.