Moring Poring
Moring Poring

Reputation: 1

How can a non-member function achieve what a friend function of a class does?

For example this class. Is there a possible way for a non-member function to do the task of the friend function?

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;
}

Upvotes: 0

Views: 100

Answers (3)

IllusiveBrian
IllusiveBrian

Reputation: 3214

If you mean access private members of the class, that cannot be done. If you want a non-member non-friend function which does the same thing Reset does in this particular case, this should work:

void notFriendReset(Accmulator& acc)
{
    acc = Accmulator();
}

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

Oh my, this sounds like homework: a contrived question with an answer that you would have to know in order to ask the question.

First, note that a friend function is a non-member, since it’s not a member.

Anyway,

void Reset( Accumulator& a )
{
   a = Accumulator();
}

Upvotes: 4

Ron Struempf
Ron Struempf

Reputation: 146

A non-member, non-friend function cannot access or modify private data members. Is there a reason you do not want to provide a member function of void Reset() {m_nValue=0;} to the public interface of the class?

Upvotes: 1

Related Questions