简体   繁体   中英

C++ base class pointers, collection classes

I have a base class of Animal and derived class of Dog, Cat.

I also have a DogCollection, CatCollection class to manage operations such as adding a new cat etc, reading a cat, and removing a cat from the database, searching for a specific cat using a pointer to the Dog and Cat class.

I have been asked to use base class pointers to manage the classes in a single container. Is it better practice to perform the read of and write operations in the Dog and Cat classes instead of a separate DogCollection and CatCollection classes for this purpose?

In common c++, you would typically use templated containers to hold objects, like this:

#include <vector>

class Cat;
class Dog;
class Animal;

typedef std::vector<Cat*> CatCollection;
typedef std::vector<Dog*> DogCollection;
typedef std::vector<Animal*> AnimalCollection;

I used std::vector as the container, but there are others available.

Then you would manipulate the container as a container and perform the operations on the items themselves, like:

AnimalCollection coll;

//add elements
Cat *cat = ...;
Dog *dog = ...;

coll.push_back(cat);
coll.push_back(dog);

//do something with the first item of the collection
coll[0] -> doStuff();

//do something on all items
for (Animal *c: coll) {
    c -> doStuff();
}

//Don't forget to delete allocated objects one way or the other
//std::vector<std::unique_ptr<Animal>> can for example take ownership of pointers and delete them when the collection is destroyed

Creating a specific collection class for a specific type can be done in specialized cases but it's not usual.

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM