I have few different classes that inherit from some Base class. Base class know who inherit him.
My task is store this in some queue and restore data later.
Here is the best I can come up with:
#include <iostream>
#include <queue>
enum class type{
some = 0,
other
};
struct Base{
const type Type;
Base(type t): Type(t) {};
};
struct Some : public Base {
int SomeData;
Some(): Base(type::some) {};
};
struct Other : public Base {
int OtherData;
Other(): Base(type::other) {};
};
std::queue<Base*> baseQueue;
void Store() {
Some *s = new Some();
s->SomeData = 1;
Other *o = new Other();
o->OtherData = 2;
baseQueue.push(s);
baseQueue.push(o);
}
void Process() {
while (!baseQueue.empty()) {
Base *b = baseQueue.front();
if (b->Type == type::some) {
Some *ps = (Some*) b;
std::cout << "Some data: " << ps->SomeData << '\n';
} else {
Other *po = (Other*) b;
std::cout << "Other data: " << po->OtherData << '\n';
}
delete b;
baseQueue.pop();
}
}
int main() {
Store();
Process();
return 0;
}
It looks ugly because:
- I works with pointers.
new
anddelete
in different sections (In real code - in different units). Someone can push to queue likeSome s; baseQueue.push(&s)
and I will fail atdelete
. Have no idea how to avoid this.- I have no idea why I don't have memory leak (I delete only
Base*
notSome*
orOther*
) - this even don't looks like c++.
So. My question is what is common practice in such cases? Maybe container that solve such things already exist, and I am just bad in googling?