1

I need help, if I have:

class gameObject{
    public: //get and set;
    private: int x;
    int y;
    string texture;
}

class gun:public gameObject{
    public: //get and set;
    private: int ammo;
}

class armor:public gameObject ... ,
class boots:public gameObject...

How I can create a linked list of multiple derived objects from base class gameObject ? For example user have a menu: [1. Add object 2.Delete object]. If user choose 1 another menu appear [Type: 1-Gun 2-Armor]. After 4 objects added the list will be: 1.Gun 2.Armor 3.Gun 4.Boots. I need an example to understand the concept.

Thanks.

2
  • 4
    std::list<gameObject*> Commented Jun 3, 2015 at 14:14
  • 3
    std::list<std::unique_ptr<GameObject>> Commented Jun 3, 2015 at 14:34

3 Answers 3

1

How I can create a linked list of multiple derived objects from base class gameObject ?

You would use std::forward_list (singly linked list) or std::list (doubly linked list) in conjunction with a smart pointer like std::unique_ptr or std::shared_ptr (depending on owning semantic), as demonstrated below:

std::list<std::unique_ptr<gameObject>> list;

and then you would allocate objects using:

list.emplace_back(std::make_unique<gameObject>(...));
Sign up to request clarification or add additional context in comments.

Comments

1

Other peoples answers were good, but in case they were answering the wrong question here:

A pointer to the base type (smart or otherwise) can point to any of the derived types too, so you need to make a list of pointers to the base type.

You can't make a list of the base type itself, because the derived types are probably bigger and wouldn't fit. The language won't even let you try.

std::list<GameObject *> is ok.
std::list<GameObject> is not.

Comments

0

You'll want to use auto pointers for this.

list<unique_ptr<gameObject>> foo;

foo.push_back(make_unique<gun>());
foo.push_back(make_unique<armor>());

for(auto& i : foo){
    if(dynamic_cast<gun*>(i.get())){
        cout << "gun" << endl;
    }else if(dynamic_cast<armor*>(i.get())){
        cout << "armor" << endl;
    }
}

This example adds a gun and then an armor to foo as unique_ptr<gameObject>s.

In the for-loop we use a dynamic_cast to discern the type. The code will output:

gun
armor

You can see an example of this code here: http://ideone.com/trj9bn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.