Athmos
Athmos

Reputation: 35

How can I write a dynamic heterogenous collection inside C++ without using STL?

Basically I have to store different movies in a heterogenous collection dynamically, I already have the different movie types (documentary and family) and the class which "masks" the difference (movie) so it can be stored in one place (record). I'm having trouble with my addMovie(Movie *mov) function. I don't know how to start.

My Record class:

class Record {
    String name;              
    size_t siz;                     
    Movie* movies;         
    Record(const Record&);
    Record& operator=(const Record&);
public:
    Record(String n): name(n), siz(0) {movies = new Movie[siz+1];}
    void addMovie (Movie *mov);
    void removeMovie (Movie *mov);
    void listMovies();
    void searchMovie (const char* title);
    void emptyRecord();
    void writeFile();
    void readFile();
    virtual ~Record() {emptyRecord();}
};

Movie class:

class Movie {
protected:
    String name;        
    String release;     
    String genre;       
public:
    Movie(){}
    Movie(String n, String r, String g): name(n), release(r), genre(g) {}
    virtual void write() {}
    virtual ~Movie() {}
};

Documentary class: (the family class is similar, it stores an int age_restriction and the write function writes that)

class Documentary: public Movie {
    String description;
public:
    Documentary(String n, String r, String d = "Add description up to 50 characters!"): Movie(n,r,"Documentary"), description(d) {}
    String getDescription () const {return description;}                                                                    
    void setDescription (String newdescr);
    void write();                                                                                                                                           
    virtual ~Documentary(){}
};

(PS: if you have any good sources for dynamic heterogenous stores I'm all ears)

Upvotes: 1

Views: 171

Answers (1)

Hack06
Hack06

Reputation: 1062

Not so clear requirements, but for storing heterogeneous data in one single container, I would advise std::tuple (https://en.cppreference.com/w/cpp/utility/tuple). Let me know if it's what you were looking for ;)

EDIT: a possible solution without STL.

#include <iostream>
using namespace std;

class Base {

};

class A : public Base {

};

class B : public Base {

};

int main(){
    const size_t arraySize = 10;
    Base* array[arraySize];

    //allocate
    array[0] = new A();
    array[1] = new B();
//  ...some more stuff here

    //dispose
    for (Base* ptr : array) {
        if (ptr != nullptr) {
            delete ptr;
            ptr = nullptr;
        }
    }
}

Upvotes: 0

Related Questions