Friend Functions and Friend Classes Interview Questions

    Question 1C++ OOPS Friend Function Concept

    What is the main purpose of a friend function in C++?

    Question 2C++ OOPS Friend Function Syntax

    Which keyword is used to declare a friend function inside a class?

    Question 3C++ OOPS Friend Function Example

    What will be the output of this code?

    #include <iostream> using namespace std; class Box { int length; public: Box() { length = 10; } friend void printLength(Box); }; void printLength(Box b) { cout << b.length; } int main() { Box b; printLength(b); }

    Question 4C++ OOPS Friend Function and Encapsulation

    Does declaring a function as a friend violate encapsulation?

    Question 5C++ OOPS Friend Function Multiple Classes

    What will be the output?

    #include <iostream> using namespace std; class A { int x = 5; friend class B; }; class B { public: void show(A a) { cout << a.x; } }; int main() { A a; B b; b.show(a); }

    Question 6C++ OOPS Friend Class Concept

    Which statement is true about friend classes in C++?

    Question 7C++ OOPS Friend Function and Object Passing

    What will be the output?

    #include <iostream> using namespace std; class Number { int value; public: Number(int v) { value = v; } friend int getValue(Number n); }; int getValue(Number n) { return n.value; } int main() { Number n(42); cout << getValue(n); }

    Question 8C++ OOPS Friend Function vs Member Function

    Which of the following is true?

    Question 9C++ OOPS Operator Overloading with Friend Function

    What will be the output?

    #include <iostream> using namespace std; class Complex { int real; public: Complex(int r) : real(r) {} friend Complex operator+(Complex c1, Complex c2); void show() { cout << real; } }; Complex operator+(Complex c1, Complex c2) { return Complex(c1.real + c2.real); } int main() { Complex a(3), b(4); Complex c = a + b; c.show(); }

    Question 10C++ OOPS Limitations of Friend Functions

    Which of the following is NOT true about friend functions in C++?