Mail Archives: djgpp/1999/01/22/23:04:15
On 21 Jan 1999 02:05:28 GMT, Shue-Cheng CHEN
<scchen AT ohriki DOT t DOT u-tokyo DOT ac DOT jp> uttered the following words:
>Hi!
>
> We know "Force" and "Velocity" are both "Vectors" in mathematics, so
>I defined them to own all behaviors and data of Vector (has been defined),
>without duplicating the code, as follows,
>
> class Force : public Vector {...};
> class Velocity : public Vector {...};
>
>Therefore, the operators of Vector, for example, operator+(Vector&, Vector&)
>can be used for Force and Velocity, like
>
> Force + Force // Ok
> Velocity + Velocity // Ok
>
> But "Force" and "Velocity" are different physical realities, so
>
> Force + Velocity // Wrong
>
>I would like to deploit the common implementation of them to avoid
>duplicating their code, but how should I do to prevent from Force +
>Vector meaningless operation?
>
> Thanks a lot!
>
>Best Regards,
>
>Shue-Cheng CHEN
>
It seems to me as what you are doing is trying to reuse (is this
spelt/spelled right?) the Vector implementation (the code) and
*NOT* its interface (what clients should do with it) as you don't
want people adding different types of Vectors.
So, this leaves you with two possibilities:
1-
class Force, private Vector // private inhearince
{
public:
//...
Force operator+(const Force&) const;
//...
};
or
2-
class Force
{
Vector m_vec; // having a Vector as a member function
//...
};
They both do more or less the same, and you dispach the
operations to your Vector, be it a base class or a member. But
what you're doing is probably going to work very badly, consider
<code>
class Force, public Vector { /*...*/ };
class Velocity, public Vector { /*....*/ };
void f(Vector& a, Vector& b)
{
a = a + b;
return;
}
int main()
{
Force kraft(0,1);
Velocity v(1,0);
f(kraft,v); // this line changes kraft
return 0;
}
</code>
if you have any problems with this, feel free to email me
privately,
Regards,
Luis Coelho.
C++ Programming Language, 3rd Ed. by B. Stroustrup. My exercise answers at:
http://www.geocities.com/SiliconValley/Way/3972/index.html
- Raw text -