Login    New User    Forgot Password    Help      

Friend Functions

GO TO INDEX

Friend Functions

A friend function is a function that can access the private members of a class as though it were a member of that class.

Example: A function Reset() that because it's a friend with class Accumulator can access private variable m_nValue

Example

class Accumulator
{
private:
    int m_nValue;
public:
    Accumulator() { m_nValue = 0; }
    void Add(int nValue) { m_nValue += nValue; }
 
    // Make the Reset() function a friend of this class
    friend void Reset(Accumulator &cAccumulator);
};
 
// Reset() is now a friend of the Accumulator class
void Reset(Accumulator &cAccumulator)
{
    // And can access the private data of Accumulator objects
    cAccumulator.m_nValue = 0;
}

Friend classes

When you make a whole class friend with another class, it gives all of the members of the friend class access to the private members of the other class.

 

Example

class Storage
{
private:
    int m_nValue;
    double m_dValue;
public:
    Storage(int nValue, double dValue)
    {
        m_nValue = nValue;
        m_dValue = dValue;
    }
 
    // Make the Display class a friend of Storage
    friend class Display;
};
 
class Display
{
private:
    bool m_bDisplayIntFirst;
 
public:
    Display(bool bDisplayIntFirst) { m_bDisplayIntFirst = bDisplayIntFirst; }
 
    void DisplayItem(Storage &cStorage)
    {
        if (m_bDisplayIntFirst)
            std::cout << cStorage.m_nValue << " " << cStorage.m_dValue << std::endl;
        else // display double first
            std::cout << cStorage.m_dValue << " " << cStorage.m_nValue << std::endl;
    }
};


GO TO INDEX