My use case is the following. I have a pure abstract class and inherited classes like so:
class AbstractCell {
public:
// data members
virtual void fn () = 0; // pure virtual functions
}
class DerivedCell1 : public AbstractCell {
public:
// more data members
void fn () {} // implementation of all virtual functions
}
class DerivedCell2 : public AbstractCell {
public:
// more data members
void fn () {} // implementation of all virtual functions
}
Now, I want to create an array of the abstract class as a member of another class.
class AbstractGrid {
public:
AbstractCell m_cells [10][10]; // this is illegal
void printCells() {
// accesses and prints m_cells
// only uses members of AbstractCell
}
}
class DerivedGrid1 : public AbstractCell {
public:
DerivedCell1 m_cells [10][10]; // I want this class to use DerivedCell1 instead of AbstractCell
}
class DerivedGrid2 : public AbstractCell {
public:
DerivedCell2 m_cells [10][10]; // I want this class to use DerivedCell2 instead of AbstractCell
}
How should I go about achieving this?
Constraints:
- For runtime efficiency, I want to use fixed-size arrays and not dynamic memory allocation (
newor smart pointers). - I want a solution other than using template classes.
I'm currently using templates, but I'm wondering if there's a better way.
AbstractGrida template that gets passed the non-abstract derived cell types? It won't be using any polymorphism though, for that you must use poinster (or references).