|
From: <or...@vp...> - 2004-05-09 10:28:11
|
Hi!
I have a question regarding operator overloading and inheritance. I have=20
a base class with some data. And I also have a derived class from base,=20
which extends base with even more data. I have defined an operator+ for=20
the base.
My question is: how can I define an operator+ for the drived class, so=20
it will copy both the base and dervied data. Must I call the base=20
operator+ from the derived operator+ explicitly?
I have thought of something like this:
class Base
{
public:
Base operator+( const Base& b )
{
Base sum;
=09
sum.m_BaseData1 =3D b.m_BaseData1 + m_BaseData1;
sum.m_BaseData2 =3D b.m_BaseData2 + m_BaseData2;
=09
return sum;
}
int m_BaseData1;
int m_BaseData2;
}; // Base
class Derived
{
public:
Derived operator+( const Derived& d )
{
Derived sum;
// assign "this + d" to sum:
sum =3D Base::operator+( d );
sum.m_DerivedData1 =3D d.m_DerivedData1 + m_DerivedData1;
sum.m_DerivedData2 =3D d.m_DerivedData2 + m_DerivedData2;
=09
return sum;
}
int m_DerivedData1;
int m_DerivedData2;
}; // Derived
Is that correct?
And if so, my next "problem" is, that an assignment operator needs to be=20
used in the Derived operator+. Can that be "solved" (removed) somehow?
Thanks in advance.
--
Greetings,
Bal=E1zs
|