c++inheritancetypestypeinfo

How to get the name of a derived class from a vector of base classes


So I have a vector of base classes and a couple bugs in my code, which means that I need to know which derived class is calling the polymorphic method:

class Base {
  virtual void render() {}
}

class Derived1 {
  void render() override {/*do stuff*/}
}

class Derived2 {
  void render() override {/*do stuff*/}
}

class Game {
  std::vector<Base> baseVec;

  void render() {
    for(Base b: baseVec) {
      b.render();
      //std::cout << typeid(b).name() << std::endl; prints base class' name, and requires some logic to unmangle the actual name
      //std::cout << std::type_index(typeid(b)).name() << std::endl; also prints base class' name
      //std::cout << typeNames[std::type_index(typeid(b))] << std::endl; typeNames is an unordered_map<std::type_index, std::string> - still prints the base class' name, and the list has to be punched in by hand (bad)
    }
  }
}

Solution

  • Below code is modified for your requirement as per my understanding for your requirements:

    class Base {
    public:
        virtual void render() = 0;
    };
    
    class Derived1: public Base  {
        void render() override { std::cout << "Derived1"<<std::endl; }
    };
    
    class Derived2: public Base {
        void render() override { std::cout << "Derived2" << std::endl; }
    };
    
    int main()
    {
        std::vector<Base*> baseVec;
        Derived1 d;
        Derived2 d1;
        baseVec.push_back(&d);
        baseVec.push_back(&d1);
    
            for (auto& b : baseVec)
            {
                b->render();
                std::cout << typeid(*b).name() << std::endl; 
            }
    
        return 0;
    }
    

    Output:

    Derived1
    class Derived1
    Derived2
    class Derived2
    

    The typeid is solving your name by using=> typeid(*b).name().

    typeid explained