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



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

Answer / 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

More OOPS Interview Questions

How Do you Code Composition and Aggregation in C++ ?

3 Answers   IBM, NET,


What is encapsulation oop?

0 Answers  


What type of Job you are providing?

0 Answers  


Define a class to represent a bank account. Include the following members: Data Members: Name of the Depositor Account Number Type of Account Balance amount in the account Member Functions: To assign the initial values. To deposit an account. To withdraw an amount after checking the balance. Write a C++ main program to display account number, name and balance.

6 Answers  


What is the renewal class?

0 Answers   Ebix, IBM,






Whats oop mean?

0 Answers  


write a c++ program to find maximum of two numbers using inline functions.

3 Answers   IBM,


Why do pointers exist?

0 Answers  


Why oops is important?

0 Answers  


write a program which best describes polymorphism in real world?

2 Answers   CTS, Infosys, NexGen,


write a program in c++ to overload the function add (s1,s2) where s1 and s2 are integers and floating point values.

4 Answers  


char* ptr = "Rahul"; *ptr++; printf("%s",ptr); What will be the output

9 Answers   Persistent,


Categories