From: deepblack AT geocities DOT com (Luis Coelho) Newsgroups: comp.lang.c++,comp.os.msdos.djgpp Subject: Re: How to implement "They are all Vectors, but different realities?" Date: Mon, 18 Jan 1999 22:08:27 GMT Organization: Universidade Tecnica de Lisboa Lines: 89 Message-ID: <36a3aeb9.24467207@news.ist.utl.pt> References: <36A68B87 DOT FFBA110C AT ohriki DOT t DOT u-tokyo DOT ac DOT jp> NNTP-Posting-Host: ppp132.ist.utl.pt X-Newsreader: Forte Free Agent 1.1/32.230 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com On 21 Jan 1999 02:05:28 GMT, Shue-Cheng CHEN 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 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; } 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