C++ friend function

Created By: chatGPT

Friend functions are a special kind of function in C++ that allow non-member functions to have access to the private and protected members of a class. This concept is useful when you need to implement certain functionalities that require access to private data, but you don't want those functions to be part of the class itself. Here's a simple example to illustrate how friend functions work.
#include <iostream>

class Box {
private:
    double width;

public:
    Box(double w) : width(w) {}
    
    // Declaring a friend function
    friend void printWidth(Box box);
};

// Definition of the friend function
void printWidth(Box box) {
    std::cout << "Width of box: " << box.width << std::endl;
}

int main() {
    Box box(10.5);
    
    // Call the friend function
    printWidth(box);
    return 0;
}

In the example above:

  • We define a class called Box with a private member width.
  • A friend function named printWidth is declared inside the class, allowing it to access the private data.
  • In the main() function, we create an instance of Box and call the friend function to print the width.

This way, the friend function is able to access the private member without being a member of the class.

Introduction And SetupVariablesData TypesIntFloatDoubleCharBoolStringVoidConstantsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorControl FlowIf StatementElse StatementElse If StatementSwitch StatementFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementFunctionsFunction DeclarationFunction DefinitionFunction OverloadingInline FunctionsDefault ArgumentsRecursionPass By ValuePass By ReferenceData StructuresArraysMultidimensional ArraysStructsEnumsUnionsClassesObjectsMember FunctionsConstructorsDestructorsAccess SpecifiersPublicPrivateProtectedInheritancePolymorphismFunction OverridingVirtual FunctionsPure Virtual FunctionsOperator OverloadingTemplatesNamespaceCommentsSingle Line CommentsMulti Line CommentsSyntaxSemicolonCurly BracesParenthesesEvent HandlingCinCoutError HandlingTry BlockCatch BlockThrow StatementException HandlingPreprocessor DirectivesInclude GuardsMacro DefinitionsInline AssemblyStatic KeywordsExtern KeywordsConst KeywordsVolatile KeywordsFriend FunctionStatic MemberThis PointerDynamic Memory AllocationNew OperatorDelete Operator