As I know C++ can get the accurate information of object's dynamic type when base class has a virtual function.
class Base
{
public:
Base() {}
~Base() { std::cout << "Base Destructed" << std::endl; }
virtual void f() {}
};
class Derived : public Base
{
public:
Derived() {}
~Derived() { std::cout << "Derived Destructed" << std::endl; }
};
void PrintTypeName(Base *p)
{
std::cout << typeid(*p).name() << std::endl;
}
int main()
{
Base *p = new Derived();
PrintTypeName(p);
delete p;
}
The code above can print the correct object type, but why it can't call the correct destructor.
I tested it on g++ and Windows compiler, they gave the same result. I know if I make the Base destructor virtual
, it can destruct right way.
But I want to know why do not call the destructor by typeid
.