Hi,
I've got structure like this
class Object //abstract
{
virtual....=0;
};
class Monster : public Object {}; //also abstract
class Wumpus : public Monster {};
class Hero : public Monster {};
class Gun : public Object{};
class Cave : public Object
{
void add(Cave*);
void add(Monster*);
};

the second fnc in Cave suppouse to add any type of Monster into this cave. My question is how can I get real type of adding object that is how to check if I'm adding a Hero or a Wumpus?
Thank you.

You could have it so the constructor requires a flag to ID the allocated item... so something like...

class base {
public: 
  enum derrivableIDs {
    idBase,
    idOne,
    idTwo
  };

protected:
  derrivableIDs id;

public:
  base() : id(idBase) {
  }



  derrivableIDs getID( void ) {
    return id;
  }
};

class one : public base {
public:
  one( void ) {
    id = base::idOne;
  }
};

class two : public base {
public:
  two( void ) {
    id = base::idTwo;
  }
};

int main( void )
{
  base *o = new one;
  base *t = new two;

  std::cout<< o->getID() << "\n";
  std::cout<< t->getID() << "\n";

  delete o;
  delete t;
  
  return 0;
}

And then test against getID() for the type of monster.

Great stuff twomers. Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.