Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

operator= problem

Status
Not open for further replies.

globos

Programmer
Nov 8, 2000
260
FR
Hi,

Consider the following code :

Code:
class A
{
public:
  virtual A& operator= (const A& other)
  {
    return *this;
  }
};

class B : public A
{
};

int main ()
{
  A a;
  B b;

  b = a;
  return 0;
}
When compiling it with VC++ 6, I get the error :
Code:
lign(19) : error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class A' (or there is no acceptable conversion)
I don't understand the problem, as B inherits
Code:
A::operator= (const A& other)
. If I duplicate this routine in B, then there is no errors.
What is behind the problem? Does operators inheritance follows specific rules? Apparently yes, because the following code is valid :
Code:
class A
{
public:
  virtual A& operator= (const A& other)
};

class B : public A
{
public:
  virtual B& operator= (const B& other)
};
Code:
operator=
accepts its argument to be covariant, which is forbidden with non-operator routines.


--
Globos
 
operators are not inherited. If you want to use opeartor = of class A, try to do like this:
((A&)b) = a;


Ion Filipski
1c.bmp
 
> operators are not inherited.
Again a bizzarery of C++, the cool thing with C++ is that one has never finished to learn it, every day you learn a new stuff.
By the way I tried the same thing with
Code:
operator==
inside class
Code:
A
and the compiler does not complain, so the rule is some operators are not inherited.
What a mess.

> ((A&)b) = a;
It works, but casts are too ugly, so I am going to duplicate operator='s code. Or maybe use a simple routine like
Code:
void copy (const A& a)
.

--
Globos
 
Taken from the VC.NET help files:

All overloaded operators except assignment (operator=) are inherited by derived classes.

Dennis
 
Thanks for your clairvoyance [3eyes].
Does the help file gives a reason why operator= can't be inherited? I'm just curious about it.

--
Globos
 
do you need a reason? I believe any reason will not help you.

Ion Filipski
1c.bmp
 
Don't be so prosaic. Curiosity is the key to success. I think I should put this in my signature.

--
Globos
 
The assigment operator can't be inherited because it so similar to a (copy) constructor's behavior.

Key reson it can't be inherited:
The base class' assignment operator knows nothing about the derived class' members, so how could it be used to assign them some values?



/Per

"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top