I am a beginner in C++ object oriented programming. I was studying "Abstract Classes" where the example code is:
#include <iostream>
using namespace std;
class Enemy {
public:
virtual void attack() = 0;
};
class Ninja: public Enemy {
public:
void attack() {
cout << "Ninja!"<<endl;
}
};
class Monster: public Enemy {
public:
void attack() {
cout << "Monster!"<<endl;
}
};
int main()
{
Ninja n;
Monster m;
Enemy *e1 = &n;
Enemy *e2 = &m;
e1->attack();
e2->attack();
return 0;
}
What I want to understand is why can't I just use the objects of derived classes to access directly the derived class members with "." operator (It works, but it is not advised why?).
Like this:
int main()
{
Ninja n;
Monster m;
Enemy *e1 = &n;
Enemy *e2 = &m;
//e1->attack();
//e2->attack();
n.attack();
m.attack();
return 0;
}
I know there will be situations where we need to go through the base class to access the members of derived classes (I think this is the normally used by all the programmers), but I have no idea on real world implementation of that kind of cases (Why can't we go direct, why is through pointers of base class?).
I would be very glad if someone can clarify my doubt.