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
Write a program to implement OOPS concepts such as inheritance, polymorphism, friend function, operator overloading?
is there any choice in opting subjects like 4 out of 7
What is overriding vs overloading?
What are objects in oop?
What is methods in oop?
What is the important feature of inheritance?
Who invented oop?
What is class encapsulation?
Please send ford technologies placement paper 2 my mail id
What does enum stand for?
What is inheritance write a program to show use of inheritance?
How do you achieve polymorphism?
What is overloading in oop?
I have One image (means a group photo ) how to split the faces only from the image?............ please send the answer nagadurgaraju@gmail.com thanks in advace...
just right the logic of it 1--> If few people are electing then every time ur candidate should win 2--> arrange books in box, if box carry weight == books weight then take another box..... find the no of box required.