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

9th Jan 2019, 9:28 PM
frank
frank - avatar
4 Answers
+ 2
An array of objects. Like an array of int or string, when you create a class, you can create an array of it.
9th Jan 2019, 9:33 PM
Rain
Rain - avatar
+ 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.
9th Jan 2019, 10:09 PM
Rain
Rain - avatar
+ 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; }
9th Jan 2019, 10:09 PM
Rain
Rain - avatar
0
@Rain thanks
9th Jan 2019, 9:35 PM
frank
frank - avatar