{"id":25179,"date":"2023-11-08T08:58:57","date_gmt":"2023-11-08T03:28:57","guid":{"rendered":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/"},"modified":"2025-01-06T19:41:52","modified_gmt":"2025-01-06T14:11:52","slug":"friend-functions-in-cpp","status":"publish","type":"post","link":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/","title":{"rendered":"Friend Function in C++ and classes with Examples"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\" id=\"introduction\"><strong>Introduction<\/strong><\/h2>\n\n\n\n<p>In the domain of C++ programming, understanding the concept of friend functions is crucial for mastering classes and their interactions. <br><br>In this blog, we delve into the essence of friend functions in C++, exploring what they are, their significance, and how they operate within the framework of classes. <br><br>If you're wondering, \"What is friend function in C++?\" or seeking clarity on the workings of C++ friend class, you've come to the right place. <br><br>Through clear explanations and illustrative examples, we'll demystify the role of friend functions and classes, empowering you to use them effectively in your <a href=\"https:\/\/www.mygreatlearning.com\/blog\/cpp-projects\/\">C++ projects.<\/a><\/p>\n\n\n\n    <div class=\"courses-cta-container\">\n        <div class=\"courses-cta-card\">\n            <div class=\"courses-cta-header\">\n                <div class=\"courses-learn-icon\"><\/div>\n                <span class=\"courses-learn-text\">Academy Pro<\/span>\n            <\/div>\n            <p class=\"courses-cta-title\">\n                <a href=\"https:\/\/www.mygreatlearning.com\/academy\/premium\/learn-c-programming-for-beginners-to-advanced\" class=\"courses-cta-title-link\">C++ Programming Course<\/a>\n            <\/p>\n            <p class=\"courses-cta-description\">Master key C++ programming concepts like variables, functions, OOP, and control structures. Build real-world projects such as a banking system and grade management tool.<\/p>\n            <div class=\"courses-cta-stats\">\n                <div class=\"courses-stat-item\">\n                    <div class=\"courses-stat-icon courses-user-icon\"><\/div>\n                    <span>Beginner to Advanced Level<\/span>\n                <\/div>\n                <div class=\"courses-stat-item\">\n                    <div class=\"courses-stat-icon courses-star-icon\"><\/div>\n                    <span>8.1 hrs<\/span>\n                <\/div>\n            <\/div>\n            <a href=\"https:\/\/www.mygreatlearning.com\/academy\/premium\/learn-c-programming-for-beginners-to-advanced\" class=\"courses-cta-button\">\n                Start Free Trial\n                <div class=\"courses-arrow-icon\"><\/div>\n            <\/a>\n        <\/div>\n    <\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-a-friend-function-in-c\"><strong>What is a Friend Function in C++?<\/strong><\/h2>\n\n\n\n<p>In C++, a friend class allows one Class to access another class's private and protected members. This means that the friend class can access the private and protected members of the Class, and it is declared as a friend, just like a member function of that Class.<\/p>\n\n\n\n<p><strong>Syntax<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nclass ClassName1 {\n    \/\/ Class definition\n\n    friend class ClassName2; \/\/ Declaration of friend class\n};\n\nclass ClassName2 {\n    \/\/ Class definition\n};\n<\/pre><\/div>\n\n\n<p>In this syntax:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>friend class <strong>ClassName2<\/strong>; declares <strong>ClassName2<\/strong> as a friend class of <strong>ClassName1<\/strong>.<\/li>\n\n\n\n<li>This declaration allows <strong>ClassName2<\/strong> to access the private and protected members of <strong>ClassName1<\/strong>.<\/li>\n\n\n\n<li>After the friend keyword, <strong>ClassName2<\/strong> is specified, indicating that <strong>ClassName2<\/strong> has access to <strong>ClassName1<\/strong>'s private and protected members.<\/li>\n<\/ul>\n\n\n\n<p><strong>Example of C++ Code using Friend Class<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass ClassB; \/\/ Forward declaration of ClassB\n\nclass ClassA {\n    private:\n        int numA;\n    public:\n        ClassA() : numA(0) {}\n\n        \/\/ Friend class declaration\n        friend class ClassB;\n\n        void display() {\n            cout &lt;&lt; &quot;ClassA: &quot; &lt;&lt; numA &lt;&lt; endl;\n        }\n};\n\nclass ClassB {\n    private:\n        int numB;\n    public:\n        ClassB() : numB(0) {}\n\n        void setValue(ClassA&amp; objA, int value) {\n            objA.numA = value; \/\/ Accessing private member of ClassA\n        }\n\n        void display(ClassA&amp; objA) {\n            cout &lt;&lt; &quot;ClassB: &quot; &lt;&lt; numB &lt;&lt; endl;\n            objA.display(); \/\/ Accessing ClassA&#039;s member function\n        }\n};\n\nint main() {\n    ClassA objA;\n    ClassB objB;\n\n    objB.setValue(objA, 100);\n    objB.display(objA);\n\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nClassB: 0\nClassA: 100\n<\/pre><\/div>\n\n\n<p><strong>Explanation<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this example, we have two classes:<strong> Class A <\/strong>and <strong>Class B<\/strong>.<\/li>\n\n\n\n<li><strong>ClassB<\/strong> is declared a friend class inside <strong>ClassA<\/strong>, which allows <strong>ClassB<\/strong> to access <strong>ClassA's<\/strong> private member <strong>numA<\/strong>.<\/li>\n\n\n\n<li>Inside <strong>ClassB<\/strong>, the setValue function modifies the private member <strong>numA<\/strong> of <strong>ClassA<\/strong> directly, demonstrating the friend class's ability to access private members.<\/li>\n\n\n\n<li>The display function of <strong>ClassB<\/strong> also accesses <strong>ClassA's<\/strong> member function display, demonstrating that friend classes can also access member functions of the Class they are friends with.<\/li>\n\n\n\n<li>In the main function, <strong>objB<\/strong> calls <strong>setValue<\/strong> to modify<strong> objA.numA<\/strong> to <strong>100<\/strong>, and then <strong>objB.display<\/strong> is called to display both <strong>numB<\/strong> and <strong>numA<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p><strong>Learners Tip:<\/strong> Friend classes or functions have the flexibility to be declared within any segment of the base class body, irrespective of its designation as private, protected, or public. This rule applies consistently across all declarations.<\/p>\n\n\n\n<p>Join our \"<a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/introduction-to-c\">Introduction to C++<\/a>\" course today and learn how to become a proficient C++ developer!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"define-friend-function-in-c\"><strong>Define Friend Function In C++<\/strong><\/h2>\n\n\n\n<p>A friend function in C++ is a non-member function that has access to a class's private and protected members. This means that a friend function can manipulate a class's private and protected members as if it were a member function of that Class. <br><br>Here is the friend function in C++ syntax to refer<\/p>\n\n\n\n<p><strong>Syntax<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nclass ClassName {\n    private:\n        \/\/ Private members\n    public:\n        \/\/ Public members\n\n        friend return_type functionName(parameters); \/\/ Declaration of friend function\n};\n\nreturn_type functionName(parameters) {\n    \/\/ Function definition\n}\n<\/pre><\/div>\n\n\n<p>In the syntax above:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <strong>friend<\/strong> keyword precedes the declaration of the friend function inside the Class.<\/li>\n\n\n\n<li><strong>return_type<\/strong> specifies the data type returned by the friend function.<\/li>\n\n\n\n<li><strong>functionName<\/strong> is the name of the friend function.<\/li>\n\n\n\n<li><strong>Parameters<\/strong> are the variables passed to the function as arguments.<\/li>\n<\/ul>\n\n\n\n<p>By declaring a function as a friend of a class, that function gains access to all private and protected class members, enabling it to operate on them directly. This concept is beneficial in scenarios where a function needs access to class members but isn't logically a class member.<\/p>\n\n\n\n<p>Also, explore \"<a href=\"https:\/\/www.mygreatlearning.com\/blog\/c-inheritance\/\">C++ Inheritance<\/a>\" and learn how to extend the functionality of your classes effortlessly!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"the-different-types-of-c-friend-functions\"><strong>The Different Types Of C++ Friend Functions<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-global-function\">1. Global function<\/h3>\n\n\n\n<p>Global function as a friend function in C++ is declared outside of any class but granted access to a class's private and protected members through the friend keyword. This allows the global function to manipulate these members as if it were a class member function.<\/p>\n\n\n\n<p><strong>Why we use it<\/strong>?<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Global functions, such as friend functions, are handy when a function needs access to private or protected members of a class but doesn't logically belong to that Class.<\/li>\n\n\n\n<li>They promote encapsulation by providing controlled access to class internals without exposing them through public member functions.<\/li>\n<\/ul>\n\n\n\n<p><strong>Example of declaring a global function as a friend function in C++:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass MyClass {\n    private:\n        int num;\n\n    public:\n        MyClass() : num(10) {}\n\n        friend void globalFunction(MyClass obj); \/\/ Declaration of global function as friend\n};\n\nvoid globalFunction(MyClass obj) {\n    cout &lt;&lt; &quot;Accessing private member of MyClass: &quot; &lt;&lt; obj.num &lt;&lt; endl;\n}\n\nint main() {\n    MyClass obj;\n    globalFunction(obj);\n\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nAccessing private member of MyClass: 10\n<\/pre><\/div>\n\n\n<p><strong>Detailed Explanation<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In the example, <strong>MyClass<\/strong> contains a private member num.<\/li>\n\n\n\n<li>The global function <strong>globalFunction<\/strong> is declared a friend of <strong>MyClass<\/strong>, allowing it to access <strong>MyClass's<\/strong> private member num.<\/li>\n\n\n\n<li>Inside <strong>globalFunction<\/strong>, we can directly access <strong>MyClass's<\/strong> private member num using an object of <strong>MyClass<\/strong>.<\/li>\n\n\n\n<li>In the main function, an object obj of <strong>MyClass<\/strong> is created and passed to <strong>globalFunction<\/strong>, demonstrating how the global function accesses the private member of <strong>MyClass<\/strong>.<\/li>\n\n\n\n<li>The output confirms that <strong>globalFunction<\/strong> successfully accessed and displayed the private member num of <strong>MyClass<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>\"Get hands-on experience with these practical <a href=\"https:\/\/www.mygreatlearning.com\/blog\/cpp-projects\/\">C++ Projects To Work On<\/a> and sharpen your skills!\"<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-member-function-of-another-class-as-friend-function\">2. Member Function of Another Class as Friend Function<\/h3>\n\n\n\n<p>A member function of another class as a friend function in C++ refers to a scenario where a member function of one Class is declared a friend of another. This grants the friend member function access to the private and protected members of the Class, which is declared as a friend of, just like a member function of that Class.<\/p>\n\n\n\n<p><strong>Why we use it<\/strong>?<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It enables specific member functions of one Class to access private or protected members of another class, fostering controlled interaction between classes.<\/li>\n\n\n\n<li>This approach is practical when certain functionalities of one Class require direct access to the internals of another class, promoting encapsulation and modularity.<\/li>\n<\/ul>\n\n\n\n<p>Example of declaring a member function of another class as a friend function in C++:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass ClassB; \/\/ Forward declaration of ClassB\n\nclass ClassA {\n    private:\n        int numA;\n\n    public:\n        ClassA() : numA(0) {}\n\n        \/\/ Declaration of ClassB&#039;s member function as a friend function\n        friend void ClassB::display(ClassA objA);\n};\n\nclass ClassB {\n    public:\n        void display(ClassA objA) {\n            cout &lt;&lt; &quot;Accessing private member of ClassA from ClassB: &quot; &lt;&lt; objA.numA &lt;&lt; endl;\n        }\n};\n\nint main() {\n    ClassA objA;\n    ClassB objB;\n\n    objB.display(objA);\n\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nAccessing private member of ClassA from ClassB: 0\n<\/pre><\/div>\n\n\n<p><strong>Explanation<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this example, <strong>ClassA<\/strong> contains a private member <strong>numA<\/strong>.<\/li>\n\n\n\n<li><strong>ClassB's<\/strong> member function display is declared a friend of <strong>ClassA<\/strong> inside <strong>ClassA<\/strong>.<\/li>\n\n\n\n<li>This declaration allows <strong>ClassB<\/strong> display access to <strong>ClassA's<\/strong> private member number.<\/li>\n\n\n\n<li>In the <strong>main<\/strong> function, an object <strong>objA<\/strong> of <strong>ClassA<\/strong> and an object <strong>objB<\/strong> of <strong>ClassB<\/strong> are created.<\/li>\n\n\n\n<li>When <strong>objB.display(objA)<\/strong> is called, <strong>ClassB<\/strong> display successfully accesses and displays the private member <strong>numA<\/strong> of <strong>objA<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"more-examples-of-c-friend-function-in-use\">More Examples of C++ Friend Function in Use<\/h2>\n\n\n\n<p>Here are more examples to explain the friend function with examples in C++:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-1-friend-function-to-calculate-average\">Example 1: Friend Function to Calculate Average<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass AverageCalculator {\n    private:\n        int num1, num2;\n    public:\n        AverageCalculator(int a, int b) : num1(a), num2(b) {}\n\n        \/\/ Friend function to calculate average\n        friend float calculateAverage(AverageCalculator obj);\n};\n\n\/\/ Definition of friend function\nfloat calculateAverage(AverageCalculator obj) {\n    return (float)(obj.num1 + obj.num2) \/ 2;\n}\n\nint main() {\n    AverageCalculator obj(10, 20);\n    cout &lt;&lt; &quot;Average: &quot; &lt;&lt; calculateAverage(obj) &lt;&lt; endl;\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nAverage: 15\n<\/pre><\/div>\n\n\n<p><strong>Explanation:<\/strong> Here, <strong>calculateAverage<\/strong> is declared as a friend function of <strong>AverageCalculator<\/strong>, allowing it to access <strong>num1<\/strong> and <strong>num2<\/strong> directly to calculate the average.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-2-friend-function-for-matrix-addition\">Example 2: Friend Function for Matrix Addition<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass Matrix {\n    private:\n        int mat&#x5B;2]&#x5B;2];\n    public:\n        Matrix() {\n            cout &lt;&lt; &quot;Enter 4 matrix elements: &quot;;\n            for (int i = 0; i &lt; 2; ++i)\n                for (int j = 0; j &lt; 2; ++j)\n                    cin &gt;&gt; mat&#x5B;i]&#x5B;j];\n        }\n\n        \/\/ Friend function for matrix addition\n        friend Matrix addMatrices(Matrix m1, Matrix m2);\n        \n        void display() {\n            cout &lt;&lt; &quot;Matrix:&quot; &lt;&lt; endl;\n            for (int i = 0; i &lt; 2; ++i) {\n                for (int j = 0; j &lt; 2; ++j)\n                    cout &lt;&lt; mat&#x5B;i]&#x5B;j] &lt;&lt; &quot; &quot;;\n                cout &lt;&lt; endl;\n            }\n        }\n};\n\n\/\/ Definition of friend function\nMatrix addMatrices(Matrix m1, Matrix m2) {\n    Matrix result;\n    for (int i = 0; i &lt; 2; ++i)\n        for (int j = 0; j &lt; 2; ++j)\n            result.mat&#x5B;i]&#x5B;j] = m1.mat&#x5B;i]&#x5B;j] + m2.mat&#x5B;i]&#x5B;j];\n    return result;\n}\n\nint main() {\n    Matrix m1, m2, sum;\n    sum = addMatrices(m1, m2);\n    sum.display();\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nMatrix:\n5 7 \n9 11\n<\/pre><\/div>\n\n\n<p><strong>Explanation:<\/strong> Here, <strong>addMatrices<\/strong> is declared a friend function of <strong>Matrix<\/strong>, enabling it to access the private member <strong>mat<\/strong> of <strong>m1<\/strong> and <strong>m2<\/strong> to perform matrix addition.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-3-friend-function-for-increment\">Example 3: Friend Function for Increment<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass Number {\n    private:\n        int value;\n    public:\n        Number(int v) : value(v) {}\n\n        \/\/ Friend function for increment\n        friend Number increment(Number num);\n        \n        void display() {\n            cout &lt;&lt; &quot;Value: &quot; &lt;&lt; value &lt;&lt; endl;\n        }\n};\n\n\/\/ Definition of friend function\nNumber increment(Number num) {\n    num.value++;\n    return num;\n}\n\nint main() {\n    Number num(5);\n    num.display();\n    num = increment(num);\n    num.display();\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nValue: 5\nValue: 6\n<\/pre><\/div>\n\n\n<p><strong>Explanation:<\/strong> In this example, <strong>increment<\/strong> is declared as a friend function of <strong>Number<\/strong>, allowing it to modify the private member <strong>value<\/strong> to increment the number directly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-4-function-friendly-to-multiple-classes\"><strong>Example 4: Function Friendly to Multiple Classes<\/strong><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass ClassB; \/\/ Forward declaration of ClassB\n\nclass ClassA {\n    private:\n        int numA;\n    public:\n        ClassA(int num) : numA(num) {}\n\n        \/\/ Friend function friendly to ClassA and ClassB\n        friend void displayBoth(ClassA objA, ClassB objB);\n};\n\nclass ClassB {\n    private:\n        int numB;\n    public:\n        ClassB(int num) : numB(num) {}\n\n        \/\/ Friend function friendly to ClassA and ClassB\n        friend void displayBoth(ClassA objA, ClassB objB);\n};\n\n\/\/ Definition of the friend function\nvoid displayBoth(ClassA objA, ClassB objB) {\n    cout &lt;&lt; &quot;From ClassA: &quot; &lt;&lt; objA.numA &lt;&lt; endl;\n    cout &lt;&lt; &quot;From ClassB: &quot; &lt;&lt; objB.numB &lt;&lt; endl;\n}\n\nint main() {\n    ClassA objA(10);\n    ClassB objB(20);\n    displayBoth(objA, objB);\n    return 0;\n}\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nFrom ClassA: 10\nFrom ClassB: 20\n<\/pre><\/div>\n\n\n<p><strong>Explanation<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this example, we have<strong> classes A<\/strong> and <strong>B<\/strong>, each with a private member.<\/li>\n\n\n\n<li>The function <strong>displayBoth<\/strong> has declared a friend to both <strong>ClassA<\/strong> and <strong>ClassB<\/strong>, allowing it to access both classes' private members, <strong>numA<\/strong> and <strong>numB<\/strong>.<\/li>\n\n\n\n<li>In the main function, objects <strong>objA<\/strong> and <strong>objB<\/strong> of <strong>ClassA<\/strong> and <strong>ClassB<\/strong> are created, respectively.<\/li>\n\n\n\n<li>The <strong>displayBoth<\/strong> function is called with <strong>objA<\/strong> and <strong>objB<\/strong> as arguments, demonstrating how a single function can access private members of multiple classes.<\/li>\n<\/ul>\n\n\n\n<p><strong>Learners Tips<\/strong><\/p>\n\n\n\n<p>The sequence in which the friend function is declared concerning another class is critical and necessitates careful consideration. It is vital to establish both classes before defining the function, thus prompting the Use of out-of-class function definition.<\/p>\n\n\n\n<p>Furthermore, read \"<a href=\"https:\/\/www.mygreatlearning.com\/blog\/function-in-c\/\">C++ Functions<\/a>\" now to see how functions contribute to code organization and reusability in C++!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"advantages-of-friend-functions\"><strong>Advantages of Friend Functions<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Versatility in Overloaded Operators: <\/strong>Friend functions allow overloaded operators to access private members of a class, enhancing flexibility in defining custom behavior for operators like +, -, etc.<\/li>\n\n\n\n<li><strong>Interclass Interactions: <\/strong>Friend facilitates seamless communication between different classes by granting access to private and protected members, promoting modularity and encapsulation.<\/li>\n\n\n\n<li><strong>Serialization: friend function C++<\/strong> plays a vital role in serialization, enabling classes to efficiently serialize and deserialize their private data without compromising encapsulation.<\/li>\n\n\n\n<li><strong>Type Conversion: <\/strong>Friend functions enable type conversion by accessing private members. This allows for smooth conversion between different data types, enhancing code flexibility and readability.<\/li>\n\n\n\n<li><strong>Domain-Specific Language: <\/strong>Friend functions empower developers to create domain-specific languages within C++ programs, enhancing expressiveness and readability by enabling custom syntax and semantics.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"disadvantages-of-friend-functions\"><strong>Disadvantages of Friend Functions:<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Limited Polymorphism: <\/strong>Friend functions are not polymorphic, limiting their usage in scenarios requiring dynamic behavior based on the object's runtime type.<\/li>\n\n\n\n<li><strong>Inheritance: <\/strong>Friend functions can't access private members of derived classes, potentially complicating inheritance hierarchies and violating the principle of least privilege.<\/li>\n\n\n\n<li><strong>Code Complexity: <\/strong>Excessive Use of friend functions can lead to increased code complexity and reduced maintainability due to tight coupling between classes and functions. It can also hinder code comprehension and debugging.<\/li>\n<\/ul>\n\n\n\n<p>Accelerate your C++ programming skills with our curated selection of <a href=\"https:\/\/www.mygreatlearning.com\/blog\/books-on-cpp\/\">top book recommendations <\/a>designed to accelerate your learning curve.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"wrapping-up\"><strong>Wrapping Up<\/strong><\/h2>\n\n\n\n<p>Through this exploration, you've gained insights into the significance and syntax of friend method C++, understanding their role in enabling interactions between classes while maintaining encapsulation. <br><br>Whether you're just starting to grasp the fundamentals or seeking to deepen your expertise in C++ programming, exploring Great Learning's <a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/c-tutorial\">free C++ tutorial<\/a> and <a href=\"https:\/\/www.mygreatlearning.com\/software-engineering\/courses\">software engineering course<\/a> can be immensely beneficial. <br><br>Our resources offer a structured pathway from understanding the basics of friend functions in C++ to mastering advanced concepts, empowering you with invaluable skills for software engineering endeavors. To continue your journey and explore structured learning materials, visit our platform offering <a href=\"https:\/\/www.mygreatlearning.com\/academy\">free online courses<\/a> in programming and much more.<br><br>Join<a href=\"https:\/\/www.mygreatlearning.com\/\"> Great Learning<\/a>'s community of learners and master C++ programming today.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faqs\">FAQs<\/h2>\n\n\n\n<div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1714977466118\"><strong class=\"schema-faq-question\">Q: Can a friend function be declared within a class?<\/strong> <p class=\"schema-faq-answer\">A: No, a friend function C++, cannot be declared within a class. Friend functions are declared outside the Class but can be granted access to its private and protected members through a declaration inside the Class using the friend keyword.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1714977507441\"><strong class=\"schema-faq-question\">Q: Can friend functions be defined inside a namespace?<\/strong> <p class=\"schema-faq-answer\">A: Yes, friend functions can be defined inside a namespace. They can be declared as friends of classes within the same namespace or outside the namespace. Defining friend functions inside a namespace allows for better organization and encapsulation of related functionalities.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1714977551044\"><strong class=\"schema-faq-question\">Q: Can friend functions be declared in a header file?<\/strong> <p class=\"schema-faq-answer\">A: Yes, friend functions can be declared in a header file like any other function. When declaring a friend function in a header file, it provides visibility to different source files that include the header file, allowing them to access the private and protected members of the Class. However, the friend function definition should be implemented in a source file (.cpp) to avoid multiple definition errors.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1714977570083\"><strong class=\"schema-faq-question\">Q: Can a friend function be virtual?<\/strong> <p class=\"schema-faq-answer\">A: No, friend functions cannot be virtual. Virtual functions are member functions of a class and participate in dynamic dispatch, which allows them to be overridden in derived classes. On the other hand, friend functions are not members of a class and do not participate in polymorphism.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1714977596544\"><strong class=\"schema-faq-question\">Q: Do derived classes inherit friend functions?<\/strong> <p class=\"schema-faq-answer\">A: No, friend functions are not inherited by derived classes. Inheritance in C++ does not affect friend relationships. Each Class must explicitly declare friend functions if they need access to private or protected members.<\/p> <\/div> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In the domain of C++ programming, understanding the concept of friend functions is crucial for mastering classes and their interactions. In this blog, we delve into the essence of friend functions in C++, exploring what they are, their significance, and how they operate within the framework of classes. If you're wondering, \"What is friend [&hellip;]<\/p>\n","protected":false},"author":41,"featured_media":25343,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[25860],"tags":[36801],"content_type":[],"class_list":["post-25179","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software","tag-c-programming"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Friend Function in C++ and classes with Examples<\/title>\n<meta name=\"description\" content=\"Friend Function in C++: A friend function in C++ is defined as a function that can access private, protected, and public members of a class.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Friend Function in C++ and classes with Examples\" \/>\n<meta property=\"og:description\" content=\"Friend Function in C++: A friend function in C++ is defined as a function that can access private, protected, and public members of a class.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"Great Learning Blog: Free Resources what Matters to shape your Career!\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/GreatLearningOfficial\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-08T03:28:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-01-06T14:11:52+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1254\" \/>\n\t<meta property=\"og:image:height\" content=\"836\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Great Learning Editorial Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/Great_Learning\" \/>\n<meta name=\"twitter:site\" content=\"@Great_Learning\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Great Learning Editorial Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/\"},\"author\":{\"name\":\"Great Learning Editorial Team\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\"},\"headline\":\"Friend Function in C++ and classes with Examples\",\"datePublished\":\"2023-11-08T03:28:57+00:00\",\"dateModified\":\"2025-01-06T14:11:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/\"},\"wordCount\":1848,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/iStock-667849954.jpg\",\"keywords\":[\"C++ Programming\"],\"articleSection\":[\"IT\\\/Software Development\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#respond\"]}]},{\"@type\":[\"WebPage\",\"FAQPage\"],\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/\",\"name\":\"Friend Function in C++ and classes with Examples\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/iStock-667849954.jpg\",\"datePublished\":\"2023-11-08T03:28:57+00:00\",\"dateModified\":\"2025-01-06T14:11:52+00:00\",\"description\":\"Friend Function in C++: A friend function in C++ is defined as a function that can access private, protected, and public members of a class.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#breadcrumb\"},\"mainEntity\":[{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977466118\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977507441\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977551044\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977570083\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977596544\"}],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/iStock-667849954.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/iStock-667849954.jpg\",\"width\":1254,\"height\":836,\"caption\":\"Developing programming and coding technologies. Website design. Cyber space concept.\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Blog\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"IT\\\/Software Development\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/software\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Friend Function in C++ and classes with Examples\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"name\":\"Great Learning Blog\",\"description\":\"Learn, Upskill &amp; Career Development Guide and Resources\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"alternateName\":\"Great Learning\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\",\"name\":\"Great Learning\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"width\":900,\"height\":900,\"caption\":\"Great Learning\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/GreatLearningOfficial\\\/\",\"https:\\\/\\\/x.com\\\/Great_Learning\",\"https:\\\/\\\/www.instagram.com\\\/greatlearningofficial\\\/\",\"https:\\\/\\\/www.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/in.pinterest.com\\\/greatlearning12\\\/\",\"https:\\\/\\\/www.youtube.com\\\/user\\\/beaconelearning\\\/\"],\"description\":\"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.\",\"email\":\"info@mygreatlearning.com\",\"legalName\":\"Great Learning Education Services Pvt. Ltd\",\"foundingDate\":\"2013-11-29\",\"numberOfEmployees\":{\"@type\":\"QuantitativeValue\",\"minValue\":\"1001\",\"maxValue\":\"5000\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\",\"name\":\"Great Learning Editorial Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"caption\":\"Great Learning Editorial Team\"},\"description\":\"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.\",\"sameAs\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/\",\"https:\\\/\\\/in.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/Great_Learning\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCObs0kLIrDjX2LLSybqNaEA\"],\"award\":[\"Best EdTech Company of the Year 2024\",\"Education Economictimes Outstanding Education\\\/Edtech Solution Provider of the Year 2024\",\"Leading E-learning Platform 2024\"],\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/author\\\/greatlearning\\\/\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977466118\",\"position\":1,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977466118\",\"name\":\"Q: Can a friend function be declared within a class?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"A: No, a friend function C++, cannot be declared within a class. Friend functions are declared outside the Class but can be granted access to its private and protected members through a declaration inside the Class using the friend keyword.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977507441\",\"position\":2,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977507441\",\"name\":\"Q: Can friend functions be defined inside a namespace?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"A: Yes, friend functions can be defined inside a namespace. They can be declared as friends of classes within the same namespace or outside the namespace. Defining friend functions inside a namespace allows for better organization and encapsulation of related functionalities.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977551044\",\"position\":3,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977551044\",\"name\":\"Q: Can friend functions be declared in a header file?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"A: Yes, friend functions can be declared in a header file like any other function. When declaring a friend function in a header file, it provides visibility to different source files that include the header file, allowing them to access the private and protected members of the Class. However, the friend function definition should be implemented in a source file (.cpp) to avoid multiple definition errors.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977570083\",\"position\":4,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977570083\",\"name\":\"Q: Can a friend function be virtual?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"A: No, friend functions cannot be virtual. Virtual functions are member functions of a class and participate in dynamic dispatch, which allows them to be overridden in derived classes. On the other hand, friend functions are not members of a class and do not participate in polymorphism.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977596544\",\"position\":5,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/friend-functions-in-cpp\\\/#faq-question-1714977596544\",\"name\":\"Q: Do derived classes inherit friend functions?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"A: No, friend functions are not inherited by derived classes. Inheritance in C++ does not affect friend relationships. Each Class must explicitly declare friend functions if they need access to private or protected members.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Friend Function in C++ and classes with Examples","description":"Friend Function in C++: A friend function in C++ is defined as a function that can access private, protected, and public members of a class.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"Friend Function in C++ and classes with Examples","og_description":"Friend Function in C++: A friend function in C++ is defined as a function that can access private, protected, and public members of a class.","og_url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/","og_site_name":"Great Learning Blog: Free Resources what Matters to shape your Career!","article_publisher":"https:\/\/www.facebook.com\/GreatLearningOfficial\/","article_published_time":"2023-11-08T03:28:57+00:00","article_modified_time":"2025-01-06T14:11:52+00:00","og_image":[{"width":1254,"height":836,"url":"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg","type":"image\/jpeg"}],"author":"Great Learning Editorial Team","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/Great_Learning","twitter_site":"@Great_Learning","twitter_misc":{"Written by":"Great Learning Editorial Team","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#article","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/"},"author":{"name":"Great Learning Editorial Team","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad"},"headline":"Friend Function in C++ and classes with Examples","datePublished":"2023-11-08T03:28:57+00:00","dateModified":"2025-01-06T14:11:52+00:00","mainEntityOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/"},"wordCount":1848,"commentCount":0,"publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg","keywords":["C++ Programming"],"articleSection":["IT\/Software Development"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#respond"]}]},{"@type":["WebPage","FAQPage"],"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/","url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/","name":"Friend Function in C++ and classes with Examples","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg","datePublished":"2023-11-08T03:28:57+00:00","dateModified":"2025-01-06T14:11:52+00:00","description":"Friend Function in C++: A friend function in C++ is defined as a function that can access private, protected, and public members of a class.","breadcrumb":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#breadcrumb"},"mainEntity":[{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977466118"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977507441"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977551044"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977570083"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977596544"}],"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#primaryimage","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg","width":1254,"height":836,"caption":"Developing programming and coding technologies. Website design. Cyber space concept."},{"@type":"BreadcrumbList","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog","item":"https:\/\/www.mygreatlearning.com\/blog\/"},{"@type":"ListItem","position":2,"name":"IT\/Software Development","item":"https:\/\/www.mygreatlearning.com\/blog\/software\/"},{"@type":"ListItem","position":3,"name":"Friend Function in C++ and classes with Examples"}]},{"@type":"WebSite","@id":"https:\/\/www.mygreatlearning.com\/blog\/#website","url":"https:\/\/www.mygreatlearning.com\/blog\/","name":"Great Learning Blog","description":"Learn, Upskill &amp; Career Development Guide and Resources","publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"alternateName":"Great Learning","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.mygreatlearning.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization","name":"Great Learning","url":"https:\/\/www.mygreatlearning.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","width":900,"height":900,"caption":"Great Learning"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/GreatLearningOfficial\/","https:\/\/x.com\/Great_Learning","https:\/\/www.instagram.com\/greatlearningofficial\/","https:\/\/www.linkedin.com\/school\/great-learning\/","https:\/\/in.pinterest.com\/greatlearning12\/","https:\/\/www.youtube.com\/user\/beaconelearning\/"],"description":"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.","email":"info@mygreatlearning.com","legalName":"Great Learning Education Services Pvt. Ltd","foundingDate":"2013-11-29","numberOfEmployees":{"@type":"QuantitativeValue","minValue":"1001","maxValue":"5000"}},{"@type":"Person","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad","name":"Great Learning Editorial Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","caption":"Great Learning Editorial Team"},"description":"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.","sameAs":["https:\/\/www.mygreatlearning.com\/","https:\/\/in.linkedin.com\/school\/great-learning\/","https:\/\/x.com\/https:\/\/twitter.com\/Great_Learning","https:\/\/www.youtube.com\/channel\/UCObs0kLIrDjX2LLSybqNaEA"],"award":["Best EdTech Company of the Year 2024","Education Economictimes Outstanding Education\/Edtech Solution Provider of the Year 2024","Leading E-learning Platform 2024"],"url":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977466118","position":1,"url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977466118","name":"Q: Can a friend function be declared within a class?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"A: No, a friend function C++, cannot be declared within a class. Friend functions are declared outside the Class but can be granted access to its private and protected members through a declaration inside the Class using the friend keyword.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977507441","position":2,"url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977507441","name":"Q: Can friend functions be defined inside a namespace?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"A: Yes, friend functions can be defined inside a namespace. They can be declared as friends of classes within the same namespace or outside the namespace. Defining friend functions inside a namespace allows for better organization and encapsulation of related functionalities.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977551044","position":3,"url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977551044","name":"Q: Can friend functions be declared in a header file?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"A: Yes, friend functions can be declared in a header file like any other function. When declaring a friend function in a header file, it provides visibility to different source files that include the header file, allowing them to access the private and protected members of the Class. However, the friend function definition should be implemented in a source file (.cpp) to avoid multiple definition errors.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977570083","position":4,"url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977570083","name":"Q: Can a friend function be virtual?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"A: No, friend functions cannot be virtual. Virtual functions are member functions of a class and participate in dynamic dispatch, which allows them to be overridden in derived classes. On the other hand, friend functions are not members of a class and do not participate in polymorphism.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977596544","position":5,"url":"https:\/\/www.mygreatlearning.com\/blog\/friend-functions-in-cpp\/#faq-question-1714977596544","name":"Q: Do derived classes inherit friend functions?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"A: No, friend functions are not inherited by derived classes. Inheritance in C++ does not affect friend relationships. Each Class must explicitly declare friend functions if they need access to private or protected members.","inLanguage":"en-US"},"inLanguage":"en-US"}]}},"uagb_featured_image_src":{"full":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg",1254,836,false],"thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954-150x150.jpg",150,150,true],"medium":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954-300x200.jpg",300,200,true],"medium_large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954-768x512.jpg",768,512,true],"large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954-1024x683.jpg",1024,683,true],"1536x1536":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg",1254,836,false],"2048x2048":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg",1254,836,false],"web-stories-poster-portrait":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg",640,427,false],"web-stories-publisher-logo":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg",96,64,false],"web-stories-thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2021\/02\/iStock-667849954.jpg",150,100,false]},"uagb_author_info":{"display_name":"Great Learning Editorial Team","author_link":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"},"uagb_comment_info":1,"uagb_excerpt":"Introduction In the domain of C++ programming, understanding the concept of friend functions is crucial for mastering classes and their interactions. In this blog, we delve into the essence of friend functions in C++, exploring what they are, their significance, and how they operate within the framework of classes. If you're wondering, \"What is friend&hellip;","_links":{"self":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/25179","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/users\/41"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/comments?post=25179"}],"version-history":[{"count":77,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/25179\/revisions"}],"predecessor-version":[{"id":114711,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/25179\/revisions\/114711"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media\/25343"}],"wp:attachment":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media?parent=25179"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/categories?post=25179"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/tags?post=25179"},{"taxonomy":"content_type","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/content_type?post=25179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}