Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!gem.mps.ohio-state.edu!usc!polyslo!ttwang
From: ttwang@polyslo.CalPoly.EDU (Thomas Wang)
Newsgroups: comp.lang.c++
Subject: Re: conceptual problem with related classes derived in parallel
Message-ID: <1989Oct2.202749.8520@polyslo.CalPoly.EDU>
Date: 2 Oct 89 20:27:49 GMT
References: <1989Oct2.181531.25198@polyslo.CalPoly.EDU>
Reply-To: ttwang@polyslo.CalPoly.EDU (Thomas Wang)
Distribution: usa
Organization: Cal Poly State University -- San Luis Obispo
Lines: 60

ttwang@polyslo.CalPoly.EDU (Thomas Wang) writes:
>If what you want is the ability to insert any class of objects into the
>list, and at the same time maintain some sort of code re-use, I have some
>sort of solution for you.

My original reply had some code bugs, so here is the correction:

class god_t
{
private:
  static char id;
protected:
  char* my_id; // the id pointer of the class
public:
  god_t();
  char id_equal(char& the_id) { return my_id == &the_id; }
  virtual char knows(char&);
};
god_t::god_t()
{ my_id = &id; }
virtual char god_t::knows(char& the_id)
{ return &the_id == &id; }
class int_t: public god_t
{
private:
  static char id;
public:
  int_t();
  virtual char knows(char&);
...
};
int_t::int_t()
{ my_id = &id; }
virtual char int_t::knows(char& the_id)
{ return (&the_id == &id) || god_t::knows(the_id); }

Now that you always know what class an object is, so you can safely
typecast in an if statement:

god_t* node;
...
if (node->knows(chocolate_t::id)) // node is a derived class of chocolate_t
  ((chocolate*) node) ->eat_chocolate();
else
  cout << "cannot eat a non-chocolate object\n";

...
if (node->id_equal(chocolate_t::id)) // node is exactly class chocolate_t
  cout << "I am class chocolate_t\n";
else
  cout << "I am not class chocolate_t\n";

eat_chocolate() should be a virtual function.


 -Thomas Wang ("This is a fantastic comedy that Ataru and his wife Lum, an
                invader from space, cause excitement involving their neighbors."
                  - from a badly translated Urusei Yatsura poster)

                                                     ttwang@polyslo.calpoly.edu