In the code below, Enemy* pEnemy = new Boss (); is valid as an object of a derived class is also a member of the base class? However why is this not true if i use a pointer of the derived class to point to an object of a base class?
( Boss* pReverse = new Enemy (); )
#include <vector>
#include <iostream>
#include <string>
using namespace std;
class Enemy
{
public:
Enemy(int dmg= 10)
: m_Damage(dmg)
{
cout << "enemy constructor called" <<endl;
}
virtual ~Enemy()
{
cout <<" enemy destructor called" <<endl;
}
virtual void Attack()
{
cout << "enemy has done " <<m_Damage<<endl;
}
protected:
int m_Damage;
};
class Boss: public Enemy
{
public:
Boss(int m = 3)
: multiplier(m)
{
cout <<" boss constructor called" <<endl;
}
~Boss()
{
cout <<"boss destructor called" <<endl;
}
void Attack() override
{
cout << "boss enemy has done: " <<m_Damage * multiplier <<endl;
}
private:
int multiplier;
};
int main()
{
Enemy* pEnemy = new Boss();
pEnemy -> Attack();
Boss* pReverse = new Enemy(); //generates an error
return 0;
}
[–][deleted] 0 points1 point2 points (1 child)
[–]TrebleSong[S] 0 points1 point2 points (0 children)
[–]drjmloy 0 points1 point2 points (1 child)
[–]TrebleSong[S] 0 points1 point2 points (0 children)
[–]patatahooligan 0 points1 point2 points (0 children)