Download presentation
Presentation is loading. Please wait.
1
Friend Functions
2
Recall Private Access Woes
//fraction.h ... class Fraction { private: int m_Numerator; int m_Denominator; }; //fraction.cpp ... Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs) { Fraction temp; temp.m_Numerator = lhs.m_Numerator * rhs.m_Numerator;
3
Recall Private Access Woes
//fraction.h ... class Fraction { private: int m_Numerator; int m_Denominator; }; //fraction.cpp ... Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs) { Fraction temp; temp.m_Numerator = lhs.m_Numerator * rhs.m_Numerator;
4
Friend Functions A friend function is a nonmember function to a class that has been given direct access rights to the private section of the class. The keyword friend is always used inside the class definition of the class granting the access rights. Never use the word friend outside of a class definition.
5
Friends! //fraction.h ... class Fraction {
friend Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs); private: int m_Numerator; int m_Denominator; }; //fraction.cpp ... Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs) { Fraction temp; temp.m_Numerator = lhs.m_Numerator * rhs.m_Numerator;
6
Friends! //fraction.h ... class Fraction {
friend Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs); private: int m_Numerator; int m_Denominator; }; //fraction.cpp ... Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs) { Fraction temp; temp.m_Numerator = lhs.m_Numerator * rhs.m_Numerator;
7
Full Function //fraction.h ... class Fraction {
friend Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs); }; //fraction.cpp ... Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs) { Fraction temp; temp.m_Numerator = lhs.m_Numerator * rhs.m_Numerator; temp.m_Denominator = lhs.m_Denominator * rhs.m_Denominator; return temp; }
8
Don’t Do This //fraction.h ... class Fraction {
friend Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs); }; //fraction.cpp ... friend Fraction mult_fracs(const Fraction & lhs, const Fraction & rhs) { Fraction temp; temp.m_Numerator = lhs.m_Numerator * rhs.m_Numerator; temp.m_Denominator = lhs.m_Denominator * rhs.m_Denominator; return temp; }
9
End of Session
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.