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
What is the highest level of cohesion?
What is meant by multiple inheritance?
What is abstract class in oop?
What is encapsulation in simple terms?
Why oops is important?
What is oops concept with example?
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).
How do you answer polymorphism?
What is oops and its features?
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!!!)
Why do we use inheritance?
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.
What is overriding in oop?
What does oop mean in snapchat?
What is a class in oop?