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
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.
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();
}
}