Kai-Uwe Bux wrote:[color=blue]
> Calum wrote:
>[color=green]
> > Victor Bazarov wrote:[color=darkred]
> >> Calum wrote:
> >> > I have a base class called Number that has subclasses Integer and
> >> > Float. I want to be able to provide a virtual operator- in the base
> >> > class so that I can subtract one Integer from another and subtract one
> >> > Float from another (I'm not too bothered about subtracting an Integer
> >> > or Float from each other). Has anyone any idea on how to do this?
> >>
> >> Yes. You already managed to declare the d-tor virtual, what's stopping
> >> you from declaring operator- virtual?
> >>
> >> > My
> >> > code is below - the actual code that I want to add the operator- to is
> >> > a lot more complex but I thought I would keep things simple.
> >> >
> >> > class Number
> >> > {
> >> > public:
> >> > virtual ~Number() {}
> >> > };
> >> >
> >> > class Integer : public Number
> >> > {
> >> > public:
> >> > Integer(int value) : m_value(value) {}
> >> >
> >> > private:
> >> > int m_value;
> >> > };
> >> >
> >> > class Float : public Number
> >> > {
> >> > public:
> >> > Float(float value) : m_value(value) {}
> >> >
> >> > private:
> >> > float m_value;
> >> > };
> >>[/color][/color]
> [snip][color=green]
> > All I really want to know is can I call the - operator on two Number
> > pointers that are both pointing to Integer and how would I go about
> > this?[/color]
>
> Since arithmetic operators like + take two arguments, the first problem is
> that you want to choose a virtual function based on the dynamic types of
> *two* objects, not just one. Google for double dispatch to get info on that
> one.
>
> However, why do you want to use pointers to numbers and virtual functions
> anyway? I would prefer to just declare two types Integer and Float that
> happen to implement similar interfaces and then, I would define conversion
> functions from Integer to Float and rounding routines the other way round.
> What do you gain by using runtime polymorphism?
>
>
> Best
>
> Kai-Uwe Bux[/color]
Thanks Kai-Uwe,
Yes, I've already started looking into using double dispatch and it
looks promising.
The problem I have doesn't actually involve Integer and Float, but
something a bit more complex - I thought I would just post a simpler,
analogous problem... Anyway, I found an interesting approach by someone
who posted around ten years ago, though their solution had a few bits
of code missing! Message ID:
31FF69BC.465C@natinst.com if you are
interested...
Regards,
Calum.