this code is working fine and prints "yes":
#include <iostream>
using std::cout;
using std::endl;
class A {
public:
virtual void talk() { cout << "person talking" << endl;}
};
class B : public A {
public:
void work() { cout << "employee working" << endl; }
};
int main() {
A* pA = new B();
if (typeid(*pA) == typeid(B))
cout << "yes" << endl; // this is printed
else
cout << "no" << endl;
}
but if i remove the virtual keyword it will print "no"
#include <iostream>
using std::cout;
using std::endl;
class A {
public:
void talk() { cout << "person talking" << endl;}
};
class B : public A {
public:
void work() { cout << "employee working" << endl; }
};
int main() {
A* pA = new B();
if (typeid(*pA) == typeid(B))
cout << "yes" << endl;
else
cout << "no" << endl; // this is printed
}
why is that happening?
why does the virtualness of a method impact the type of the object?
EDIT:
To make things more confusing, this works fine:
((B*)(pA))->work(); // works fine, prints "employee working"
So why is the *pA regarded only as class A object (when there is no virtual keyword) but can still call child's work() method?