4

I want to create a number of objects of a class, but this number won't be known until runtime. Intuition tells me that I should use the following loop to create my objects:

for (int count = 0;  count < no_of_objects; count ++)
{
    ClassName object_name[count]
}

This, however does not work as the compiler doesn't appear to like using variables as object names. Is there a way I can create these objects using a loop, or do I have to use some other method.

Please bear in mind that I have not been using C++ for long and have only recently been introduced to programming, so my knowledge of the language is somewhat limited - so far, the array is the only data structure I have been taught - no vectors, etc.

4 Answers 4

7

It's time to learn vectors:

std::vector<ClassName> objects (no_of_objects);

Now use objects[0] through objects[no_of_objects - 1]; note that objects.size() equals no_of_objects. When you're ready, look at vector's methods, etc., but for now, this plus knowing the header to include (<vector>) is enough to use objects as a dynamic array.

Sign up to request clarification or add additional context in comments.

9 Comments

@Fred while I agree vectors should in general be used in a situation like this, since this is tagged homework, vectors may not be allowed. That may be the next class assignment :)
@pstrjds: It's tagged [homework], not [vectors-not-allowed]. Chris said he doesn't yet know vectors, not that he can't use them. In the absence of that latter constraint, I'm answering to learn basic vector use (covered by all of the two sentences above).
There's no restriction been placed on what structures we're allowed to use. I'll look into vectors. Thanks.
@pst: Bjarne Stroustrup disagrees with you. He introduces std::vector on page 116 of his current book, while arrays and pointers are deferred until page 569. His university courses are structured the same way.
@pstrjds: Pick up Accelerated C++ by Koenig/Moo and read that. It's an introductory book, but if even you're a seasoned C++ developer, you will very likely still enjoy reading it. Koenig&Moo were the first to get teaching C++ right and taught the usage of certain components long before they taught their inner workings. To us who had been schooled the old way it might at first seem strange to teach using std::vector<> before teaching templates, but then there's so many languages where string is just a unchallenged black box. I taught C++ this way for many years, and had much success.
|
2

In C++ you will have to allocate this dynamically if you do not know the number of objects until runtime. You would need code similar to this:

ClassName* pmyClasses = new ClassName[no_of_objects];

This will allocate an array to hold your class objects, you then need to initialize them.

for (int i=0; i < no_of_objects; i++)
{
    pmyClasses[i] = new ClassName();
}

You can then access them via the array indexer:

for (int i=0; i < no_of_objects; i++)
{
     pmyClasses[i].SomeFunction();
}

An important thing to note here is that if you use new to allocate memory, then you need to use delete to deallocate it. Since this is an array declaration then you need to use the delete [] operator.

for (int i=0; i < no_of_objects; i++)
{
    delete pmyClasses[i];
}
delete [] pmyClasses;

If you are using this inside or a class it would be important to have the delete in the destructor of the class:

class UsingMyClass
{
    private:
        ClassName* pmyClasses;

    public:
        UsingMyClass(int no_of_objects)
        {
            pmyClasses = new ClassName[no_of_objects];
            for (int i=0; i < no_of_objects; i++)
            {
                 pmyClasses[i] = new ClassName();
            }
        }

        ~UsingMyClass()
        {
            for (int i=0; i < no_of_objects; i++)
            {
                 delete pmyClasses[i];
            }

            delete [] pmyClasses;
        }
 }

By doing this, when the UsingMyClass object goes out of scope (assuming it was not created via a call to new or malloc) then the array of ClassName objects will be cleaned up.

Comments

0

If your class has a default constructor (and you want to default construct the instances), you can use an array new i.e. new ClassName[some_number] - which is of type ClassName*).

If it doesn't have a default constructor, you can fool around with placement new, or use an array of pointers and new each one manually.

Comments

0

TO allocate the memory dynamically you have to use the new keyword

ClassName = new object_name[count];

and make sure to delaocate the memory after by using delete keyword

1 Comment

You'll want ClassName* pObjects = and delete [], though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.