- Type Identification
In object-oriented programming, we often encounter situations where:
A base class pointer references a derived class object A base class reference becomes an alias for a derived class object
Key Concepts:
Static type: The declared type of a variable (expected and fixed) Dynamic type: The actual type of the object that a pointer or reference points to
Solution Approach:
Define a virtual function in the base clas to return type information All derived classes must implement this virtual function Each class provides its own implementation to return unique type identifiers
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
virtual string getType()
{
return "Animal";
}
virtual ~Animal() {}
};
class Dog : public Animal
{
public:
string getType()
{
return "Dog";
}
void bark()
{
cout << "Woof! Woof!" << endl;
}
};
class Cat : public Animal
{
public:
string getType()
{
return "Cat";
}
};
void processAnimal(Animal* p)
{
if(p->getType() == "Dog")
{
Dog* d = static_cast<Dog*>(p);
d->bark();
}
cout << "Address from dynamic_cast: " << dynamic_cast<Dog*>(p) << endl;
}
int main()
{
Animal a;
Dog d;
Cat c;
processAnimal(&a);
processAnimal(&d);
processAnimal(&c);
return 0;
}
/*Output:
0
Woof! Woof!
0x7fff5fbff8c8
0
*/
Limitations of Polymorphic Solutions:
Must provide type-checking virtual function starting from the base class All derived classes must override the type-checking function Type names across all class must be unique
- Type Identification Keywords
C++ provides the typeid keyword to retrieve type information:
typeid returns type information for the given paramter Returns a type_info object Throws an exception when the parameter is NULL
Important Notes about typeid:
Type name formatting may vary across different compilers When applied to a type name (e.g., int), returns static type information When applied to a variable (e.g., var):
No virtual function table: returns static type information Virtual function table exists: returns dynamic type information
#include <iostream>
#include <typeinfo>
using namespace std;
class Vehicle
{
public:
virtual ~Vehicle() {}
};
class Car : public Vehicle
{
public:
void drive()
{
cout << "Driving..." << endl;
}
};
void checkType(Vehicle* v)
{
const type_info& info = typeid(*v);
cout << info.name() << endl;
}
int main()
{
int counter = 0;
const type_info& t1 = typeid(counter);
const type_info& t2 = typeid(int);
cout << (t1 == t2) << endl;
Vehicle v;
Car car;
checkType(&v);
checkType(&car);
return 0;
}
/*Output:
1
7Vehicle
3Car
*/