i'm a little bit curious, how the typeid works? i mean, like, the syntax of typeid(variable).name();
is strange for me. can anybody explain it to me? and thus, it'll helps me to understand for any similar "cases"... :D
#include <iostream>
#include <typeinfo>
usingnamespace std;
class Animal{
public:
virtualvoid display(){}
};
class Cow:public Animal{};
class Dog:public Animal {};
int main(){
Animal *anm;
Cow cw;
Dog dg;
cout << "type of anm is : "<<typeid(anm).name()<<endl;
cout << "type of cw is : "<<typeid(cw).name()<<endl;
cout << "type of dg is : "<<typeid(dg ).name()<<endl;
//after initializing base pointer with address of derived class object
anm = &cw; //assigns anm with address of cw.since Animal is virtual, anm is now type of //Cow
cout<<"type of *anm when pointing to cw is: "<<typeid(*anm).name()<<endl;
anm = &dg;
cout<<"type of *anm when pointing to dg is: "<<typeid(*anm).name()<<endl;
}
output
1 2 3 4 5
type of anm is : Animal
type of cw is : Cow
type of dg is : Dog
type of *anm when pointing to cw is: Cow
type of *anm when pointing to dg is: Dog
This example shows that , initially anm is type of Animal, cw is type of Cow and dg is type of Dog as expected. But when anm is initialized to address of cw, due to property of virtual function, anm is now type of Cow but not type of Animal . So typeidcan be used to know the type of Object only at runtime. Compiler is unknown about it until runtime
struct Simple
{
void Print() const
{
std::cout << "Simple::Print()" << std::endl;
}
};
Simple &NewInstance()
{
// When I invoke this function, X will be returned
// by reference, and not a copy.
static Simple X;
return(X);
}
int main()
{
NewInstance().Print();
// Here, Print() is a method of Simple. Since NewInstance()
// returned X, an instance of Simple, by reference, I reached
// into X and called its Print() method.
}