class CParent {
public:
void Output() {
cout << "I'm Parent!" << endl;
}
virtual void VirtualOutput() {
cout << "I'm Parent!" << endl;
}
};
class CChild : public CParent {
public:
void Output() {
cout << "I'm Child!" << endl;
}
void VirtualOutput() {
cout << "I'm Child!" << endl;
}
};
class CChildChild : public CChild {
public:
void Output() {
cout << "I'm ChildChild!" << endl;
}
void VirtualOutput() {
cout << "I'm ChildChild!" << endl;
}
void CChildOnly() {
cout << "I'm only on ChildChild!" << endl;
}
};
int main() {
CParent cp;
CChild cc;
CChildChild ccc;
CParent* pCP1 = &cp;
CParent* pCP2 = &cc;
CParent* pCP3 = &ccc;
((CChildChild*)pCP1)->CChildOnly(); //<-this code actually works. HOW? WHY?
return 0;
}
The pointer variable 'pCP1' is pointing 'cp' which is 'an object of CParent'. So the 'down casting' doesn't make any sense according to what I've learned.
But it works and shows 'I'm only on ChildChild!' with no problem.
The 'cp' has only 'CParent part' on its memory construct. So it can not be 'down casted' as far as I know.
But it works. How?