Thread: checking type of class

  1. #1
    Registered User
    Join Date
    Jun 2003

    checking type of class

    There is a mammal class and dog + cat inherit mammal.

    If I had a function to which you pass a mammal pointer but it is intended to be passed a dog or cat, how could you check what type of class was passed?

  2. #2
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    I donīt know if typeid works with polimorphism, but you could store a string in the class that says what it is
    Nothing more to tell about me...
    Happy day =)

  3. #3
    Registered User
    Join Date
    Apr 2002
    I'm not sure why you would need to know. If you are passing a base class pointer to some function you should probably be changing / setting things that are common members in the base class. I guess you could use typeid if you really wanted to but, imo, for the case you are describing it would be poor design.
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

  4. #4
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    I agree with MrWizard, but if you really need to, here are a couple ideas:

    // Not a particularly good idea...
    class base
       std::string type_;
       base(std::string str) : type_(str) {}
       virtual std::string type() const;
    class a : public base
       a() : base("a") {}
    // later on...
    voif foo(base* x)
       if(x->type() == "a") ...
    The other possibility is to dynamic_cast:

    // A slightly better idea
    template<typename T, typename U>
    bool is_type(U* x)
       return (dynamic_cast<T*>(x) != 0);
    // later on...
    void foo(mammal* x)
       if(is_type<cat>(x)) ...
    Again, you really shouldn't need to no in most cases, and there usually is a better was around.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 07-29-2008, 04:37 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Erros in Utility Header File
    By silk.odyssey in forum C++ Programming
    Replies: 4
    Last Post: 12-22-2003, 06:17 AM