0
to be honest i have no clue what to call this
so I was playing around with polymorphism and inheritance and decided to do this: #include <iostream> using namespace std; class enemy{ public: void attack(){ cout<<"attack"; } }; int main() { enemy *e[3] = {*e, *e, *e}; e[0]->attack(); cout<<"\n"; e[1]->attack(); cout<<"\n"; e[2]->attack(); return 0; } I wasn't really expecting it to work but I was wondering does this have a name if so what is it? and if I were to use this in a project is this a good coding practice? edit: the thing im talking about is in the main function
4 Respuestas
+ 2
An array of objects. Like an array of int or string, when you create a class, you can create an array of it.
+ 2
Run that in a C++ compiler. Pretty interesting. Only works with public inheritance. Hope this expands your knowledge.
https://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/
^ Take a look at this link to learn a lot more about inheritance.
+ 1
#include <iostream>
#include <string>
using namespace std;
class Enemy{
public:
void attack(){
cout << name << " atacked!" \
<< endl;
}
void printStats(){
cout << "Name: " \
<< name << endl;
cout << "Health: " \
<< health << endl;
cout << "Damage: " \
<< damage << endl;
}
~Enemy(){
cout << name << \
" has been deleted!" << endl;
}
protected:
string name;
int health;
int damage;
};
class Goblin:public Enemy{
public:
Goblin(){
name = "Goblin";
health = 5;
damage = 2;
}
private:
};
class Skeleton:public Enemy{
public:
Skeleton(){
name = "Skeleton";
health = 3;
damage = 5;
}
private:
};
int main(){
Goblin* G1 = new Goblin;
Goblin* G2 = new Goblin;
Goblin* G3 = new Goblin;
Skeleton* S1 = new Skeleton;
Skeleton* S2 = new Skeleton;
Skeleton* S3 = new Skeleton;
Enemy* enemies[6] = \
{G1,S1,G2,G3,S2,S3};
for(int i = 0; i < 6; i++){
enemies[i]->printStats();
enemies[i]->attack();
delete enemies[i];
cout << endl;
}
return 0;
}
0
@Rain thanks