why freind function takes more parameter than normal member
function in c++?

Answer Posted / jeremiah

A friend function needs to know the object on which it must
operate. Class member functions have an implicit "this"
pointer which define the object on which it must operate.

Example:
---------------------------------------------------------
class Number;

// A function that adds two numbers.
// This function must be a friend of the Number class
// because it operates on a private member variable of the
// Number class.
Number Add( const Number& lhs, const Number& rhs )
{
Number result;
result = lhs.m_value + rhs.m_value;
return result;
}

// The Number class
class Number
{
public:
// Constructor - Default to 0.
explicit Number( int value = 0 )
: m_value( value )
{}

// Copy constructor
Number( const Number& copy )
: m_value( copy.m_value )
{}

// Add this number with another and return the result.
// This operator only needs 1 argument because the
// Left-hand side is assumed to be the class itself.
Number operator+( const Number& rhs ) const
{
Number result;
result.m_value = m_value + rhs.m_value;
return result;
}

private:
// Allow the Add function to access the private members
// of this class by making it a friend function.
friend Number Add( const Number&, const Number& );
int m_value;
};
-----------------------------------------------------------

As you can see from the example, the "Add" function takes
two arguments (a left-hand side operator, and a right-hand
side operator), whereas the Number::operator+ member
function only needs to know the right-hand side operator
because the left-hand side operator is assumed to be the
class instance itself.

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the highest level of cohesion?

568


What is meant by multiple inheritance?

732


What is abstract class in oop?

526


What is encapsulation in simple terms?

534


Why oops is important?

599






What is oops concept with example?

572


write a code for this:trailer recordId contains a value other than 99, then the file must error with the reason ‘Invalid RECORD_ID’(User Defined Exception).

1636


How do you answer polymorphism?

575


What is oops and its features?

578


Write a C++ program without using any loop (if, for, while etc) to print prime numbers from 1 to 100 and 100 to 1 (Do not use 200 print statements!!!)

1633


Why do we use inheritance?

626


write a program to enter a string like"sunil is a good boy and seeking for a job" not more than 10 characters including space in one line,rest characters should b in other line.if the next line starts from in between the previous word,then print whole word to next line.

1785


What is overriding in oop?

545


What does oop mean in snapchat?

675


What is a class in oop?

593