Search code examples
c++arrayspointersdynamic-memory-allocation

C++ Array of pointers to class names


I'd like to be able to hold an array of class names and simply pass an index to a function which would create an instance of a certain class. I have memory constraints so I'd like to not simply create an array of objects.

Here's my most descriptive pseudo-code:

Classes:

class Shape
{
public:
    Shape();
};

class Square : public Shape
{
public:
    Square();
};

class Triangle : public Shape
{
public:
    Triangle();
};

Main:

int main()
{
    pointerToShapeClass arrayOfShapes[2];       // incorrect syntax - but
    arrayOfShapes[0] = pointerToSquareClass;    // how would i do this?
    arrayOfShapes[1] = pointerToTriangleClass;

    cin << myNumber;

    // Depending on input, create instance of class corresponding to array index
    if (myNumber == 0) { // create Square   instance }
    if (myNumber == 1) { // create Triangle instance }

    return 0;
}

If this is confusing, I can try to elucidate. Thanks in advance!

Edit:

Really, I think I just need a pointer to a class without actually instantiating the class.


Solution

  • Sounds like you want some kind of factory:

    class Shape
    {
    public:
        Shape();
        static Shape* create(int id);
    };
    
    Shape* Shape::create(int id) {
      switch (id) {
        case 0: return new Square();
        case 1: return new Triangle();
      }
      return NULL;
    }
    

    Then when you want to create a particular Shape given user input, you can do:

    int myNumber;
    cin >> myNumber;
    Shape* shape = Shape::create(myNumber);
    

    This is it in it's simplest form. I would, however, recommend having the create function return a std::unique_ptr<Shape>, rather than a raw pointer. I would also set up static constants to represent the different IDs.

    class Shape
    {
    public:
        Shape();
        static std::unique_ptr<Shape> create(int id);
    
        enum class Id { Square = 0, Triangle = 1 };
    };
    
    std::unique_ptr<Shape> Shape::create(Shape::Id id) {
      switch (id) {
        case Shape::Id::Square: return new Square();
        case Shape::Id::Triangle: return new Triangle();
      }
      return nullptr;
    }