typeid keyword

Introduced in CS247, when introducing the Liskov Substitution Principle.

bool Circle::operator==(const Shape& other) const {
	if (typeid(other) != typeid(Circle)) return false;
	const Circle& cother=static_cast<const Circle&>(other);
	...
}

typeidreturnsstd::type_info` objects that can be compared.

Difference between typeid and dynamic_cast?

  • typeid: Is other exactly a Circle? Doesn’t consider inheritance.
  • dynamic_cast: Is other a Circle, or a subclass of Circle? Considers inheritance.

typeid uses the dynamic-type so long as the class has at least one virtual method.