This is not how polymorphism works.
How to achieve what you are trying to do
dynamic_cast<T>
uses RTTI to check whether a polymorphic type is actually of type T
:
GuidedTour * ptr = dynamic_cast<GuidedTour *>(*it);
if(ptr != NULL)
{
std::cout << "This is a guided tour" << '\n';
}
However, RTTI comes at a cost; those are checks performed at runtime and will slow down your performance, and RTTI may not be supported at all.
What you usually should do
Avoid needing to know the exact type of your polymorphic object. Provide an interface that works well regardless and rely on calling your virtual methods to do the job.
class Tour
{
public:
virtual ~Tour() {}
virtual void info() const
{
std::cout << "This is not a guided tour" << '\n';
}
};
class GuidedTour : public Tour
{
public:
void info() const
{
std::cout << "This is a guided tour" << '\n';
}
};
Tour * tour = new GuidedTour();
tour->info();
delete tour; // here you need the virtual destructor
And while we're at best practice; please avoid raw pointers. Even if you are bound to C++98, there are very good smartpointers out there; Boost for example provides shared_ptr
and weak_ptr
that closely resemble the ones in C++11.