So far I got how to create the classes ok today but I would like a vector of classes(I think). im trying to access the virtual functions with a single command to different monsters of class critters. some help on the subject would be great. I cant find what im looking for online.
#pragma once
#include "critter.h"
class goblin :
public Critter
{
public:
goblin(void);
~goblin(void);
virtualvoid MobAtt();
};
goblin.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include "goblin.h"
#include <iostream>
goblin::goblin(void)
{
goblin::setname("goblin"), goblin::sethp(4);
}
goblin::~goblin(void)
{
}
void goblin::MobAtt()
{
std::cout << "goblin takes his sword and over hand chops you in the head for 20 points" << std::endl;
}
First off, in line 15 of your main.cpp, why are you calling the destructors? I'm not even sure if that's legal...
Anyway, for a vector of classes, you obviously need a vector. Considering you are storing polymorphic classes, you need to store pointers to them. Here is how I would do your 'main.cpp':
#include <iostream>
#include <vector>
#include <memory>
#include "Critter.h"
#include "goblin.h"
int main() {
// list of Critter smart pointers
std::vector<std::unique_ptr<Critter>> mobs;
mobs.emplace_back(new goblin);
mobs.emplace_back(new Critter);
for (auto& x : mobs) {
std::cout << x->gethp() << " hp\n";
std::cout << x->getName() << " name\n";
}
std::cout << "Lets call attack for critter 0:\n";
mobs[0]->MobAtt();
std::cout << "Lets call attack for critter 1:\n";
mobs[1]->MobAtt();
std::cin.sync();
std::cin.get();
return 0;
}
Also, you need to do some looking up into how classes work, namely your goblin constructor. Initializer lists could be something to learn, too. For now, get rid of the goblin:: in setname and sethp for your goblin class constructor.
thank u very much, that worked for storing the monsters and calling there attacks.
the for (auto& x : mobs) gave me a error: can not deduce 'auto' type (initializer required), but I looped through with:
unsigned int size = mobs.size();
for (unsigned int i = 0; i < size; ++i)
{
cout << mobs[i]->getname() << endl;
}
and ill check out the initializer list. I just read some stuff on classes and so I wanted to try it out and well I had got that far and the book ended, it didn't explain how to store a polymorphic class in a vector. u have a name of a good book this stuff?