Functions and Objects

Friend Function in C++

Friend functions can access private and protected members of a class object passed into the function.


Syntax
//within class declaration
class className {
    friend functionDeclaration(passedParameters){

    }
}

//function definition, outside of class
functionDeclaration(passedParameters){
    //suppose classObject is a className object passed in as a parameter
    //private and protected members of classObject can be accessed directly
    classObject.privateMember = value;

    //in addition, newly created objects can also have their private/protected members accessed
}

Notes

Function declaration for a friend function is similar to that of a regular function, but with the 'friend' keyword.

Friend functions actually are not a member of any class.


Example
class Car {
    public: 
        friend double kphSpeed(const Car) const{}
    private:
        double mph;
}

double kphSpeed(const Car c) const {
    double kph = c.mph * 1.60934; //function can access private mph directly
    return kph;
}

See Also
Related

Functions

Documentation

Friendship and inheritance

Add to Slack

< Inheritance   |   Friend Class >

© 2019 SyntaxDB. All Rights Reserved.