Consider the following code:
#include <iostream>
class Entity
{
private:
int entityInt_;
public:
Entity()
: entityInt_(0)
{}
virtual void print() const
{
std::cout << "This is Entity class\n";
}
};
class Player : public Entity
{
private:
int playerInt_;
public:
Player()
: playerInt_(0)
{}
void print() const
{
std::cout << "This is Player class\n";
}
};
class Enemy : public Entity
{
private:
int enemyInt_;
double enemyFloat_;
public:
Enemy()
: enemyInt_(0), enemyFloat_(0.0)
{}
void exclusiveEnemy() const
{
std::cout << "This is an exclusive method of Enemy class\n";
}
void print() const
{
std::cout << "This is Enemy class\n";
}
};
int main(int argc, const char* argv[])
{
Entity* actuallyPlayer = new Player();
Enemy* enemy = static_cast<Enemy*>(actuallyPlayer);
enemy->print();
enemy->exclusiveEnemy();
}
As far as I understand, in the line:
Entity* actuallyPlayer = new Player();
the underlying object which actuallyPlayer pointer is pointing to is a Player. Player does not contain exclusiveEnemy method. Hence, I expected that, after casting the Entity class into an Enemy class and calling that method, the program would crash (because actuallyPlayer is actually pointing to a Player and not to an Enemy). However, the program works fine and prints:
This is Enemy class
This is an exclusive method of Enemy class
I would like to understand why is this code not crashing.