1

I'm a beginner in C++, for this game project that I am creating what I'd like to have is a collection of generic "GameObject" element, each with virtual methods for Update and Draw...then have classes inheriting from it with their own definitions of such methods so that when updating the world I only need to keep one collection to cycle through...

It seems like it is impossible with Vector to hold a collection of abstract classes, I tried instead to keep the Draw and Update methods virtual, but then if I create an Enemy : public GameObject instance and add it to a Vector<GameObject> and call update then I get all sorts of Linker: undefined symbol errors....

I don't know, there's something I am not grasping.... I am sure this is a type of setting that many application would require.... what is your advice on approaching this? Should I maybe try a different type of collector than Vector?

Thank you very much

EDIT:

In response to the replies below, I tried:

class GameObject{

....

virtual void update(float t):

....
}

//-------------------------------------------


class Enemy: public GameObject{

.....

void update(float d);


.....


void Enemy::update(float d){
    //Have a breakpoint here
}

//-------------------------------------------

class World{
...
vector<GameObject*> gameObjects;
...
}

//-------------------------------------------

class Level{

World levelWorld;

....

Level(){

levelWorld = new World();

}

...


Enemy* en = new Enemy();


levelWorld->visibleObjects.push_back(en);
levelWorld->visibleObjects.at(0)->update(0);

}

And I get, as I did before:

Error   25  error LNK2001: unresolved external symbol "public: virtual void __thiscall Enemy::update(float)" (?update@Enemy@@UAEXM@Z)   

Error   28  error LNK2001: unresolved external symbol "public: virtual void __thiscall GameObject::update(float)" (?update@Object3DS@@UAEXM@Z)  

....

Any suggestions?

Alex
  • 561
  • 2
  • 9
  • 28
  • Are you sure the file containing `void Enemy::update(float)` is compiled and linked with the binary. – crazyjul Nov 05 '11 at 22:18

3 Answers3

1

As stated in Effective C++(Scott Meyers), you should not create arrays of polymorphic types. In your case, using a vector<GameObject*>will work. But I would advise using auto_ptr or any other smart pointer.

crazyjul
  • 2,519
  • 19
  • 26
0

Use Vector<GameObject*> (or something that involves references/pointers) instead of Vector<GameObject>. You aren't allowed to instantiate abstract base classes.

Pubby
  • 51,882
  • 13
  • 139
  • 180
0

If you want subtype polymorphism, you need a vector of pointers. Otherwise, your objects will get sliced. Since a vector of raw pointers is not exception safe, I recommend a vector of shared pointers:

#include <vector>
#include <memory>
// ...
std::vector<std::shared_ptr<GameObject>> gameObjects;
gameObjects.push_back(std::make_shared<Enemy>());
fredoverflow
  • 256,549
  • 94
  • 388
  • 662