"Nitin Bhardwaj" <ni*************@hotmail.com> wrote in message
news:17**************************@posting.google.c om...
Thanx in advance for the response...
I wanna enquire ( as it is asked many a times in Interviews that i
face as an Engg PostGraduate ) about the overloading capability of the
C++ Language.
Why can't the = (assignment) operator be overloaded as a friend
function ?
I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it
said the following :
The operators [] , -> , = cannot be overloaded as static functions
from which i figured out that since 'friend' qualifier makes the
function a static function( i.e. a per-class member ), hence =
operator can't be overloaded as a friend function.But why is such
restrction there in the language in the first place ???
Different rules apply to the functions which are called because they are
member functions or friend functions. For instance
class X // uses friend
{
public:
X(int); // note we can make an X from an int
friend bool operator<(const X&, const X&);
};
Given the above
X x;
if (1 < x)
...
is legal. The compiler will automatically construct an X object from the int
1. But given
class Y // uses member
{
public:
Y(int); // note we can make an Y from an int
bool operator<(const Y&) const;
};
then
Y y;
if (1 < y)
...
is not legal. With a member function you do not get the automatic conversion
of the first argument, the compiler will not construct a Y object from an
int in the expression 1 < y.
You can probably guess what is coming now. If you were able to declare
operator= as a friend like this
class X // uses friend
{
public:
X(int); // note we can make an X from an int
X& operator=(X&, const X&);
};
then stupid code like this
X x;
1 = x;
would be legal!
In short requiring that operator= be a member function ensures that what you
are assigning to really is a bona fide object, not some temporary
constructed by the compiler.
john