typeid.name() not changing when iterating through a vector. Dynamic cast and typeid a base class pointer

前端 未结 2 1152
北海茫月
北海茫月 2021-01-21 11:53

Answer: In short use virtual functions! So don\'t actually use this as good design, but for learning purposes take a read!

I want to start off by saying I am using c++ a

相关标签:
2条回答
  • 2021-01-21 12:16

    For dynamic cast to work, any of the function in base class must be virtual, that mean base class must be used in polymorphic way.

    0 讨论(0)
  • 2021-01-21 12:39

    This works as intended with doSomething as a virtual function. If it is not virtual, then the compilation itself will fail (if there are no other functions in the Shape class which are virtual). Dynamic cast will fail if source type is not polymorphic.

    If it is virtual, you need not do what you are doing to determine the type. Let polymorphism do its magic. You can shorten your code like this:

    #include <iostream>
    #include <vector>
    
    class Shape { public: virtual void doSomething() {std::cout << "In Shape\n";}};
    class Circle: public Shape {public: void doSomething() {std::cout << "In Circle\n";}};
    class Square: public Shape {public: void doSomething() {std::cout << "In Square\n";}};
    
    int main() {
        std::vector<Shape *> vec;
        vec.push_back(new Square);
        vec.push_back(new Circle);
    
        for(auto tmp = vec.begin();tmp != vec.end(); ++tmp)
        {       
            (*tmp)->doSomething();        
        }
    }
    
    0 讨论(0)
提交回复
热议问题