0

I am creating a program that will make a new object each time I press a certain button. I want to name these objects sequentially and not have to hard code in a certain number of objects. Is there a way in C++ that I can do this?

I want the code to be something like this

if (key == 'n')
{
    new Object *shape1*;
}

then next time it runs through that it is

if (key == 'n')
{
    new Object *shape2*;
}

then after all objects have been made I want to have a record of the number created (global variable keeping track of count) to be able to print all of these. I haven't used C++ in a year or two so I'm not sure if there is a better way of doing this that I just forgot about or what. If you have a better way of doing this, I am open to any ideas.

Thanks!

2
  • You can use arrays of objects and place a new object into a new position. But you'll be wasting lots of memory then. Commented Mar 2, 2015 at 18:53
  • Why does it matter for you what name is given to the variables? Anyway your compiler, asfaik, is allowed to given them arbitrary names as they have no effect on the compiled program Commented Mar 2, 2015 at 18:55

1 Answer 1

1

I would discourage you from trying to name variables dynamically. Rather you can add dynamic objects to a container.

std::vector<Object*> objects;

if (key == 'n')
{
    Object* newObject = new Object;
    objects.push_back(newObject);
}

Then you can use the index essentially as the incremented variable name, e.g.

objects[3]

This will also make cleaning up your allocated memory much easier than trying to chase down an unknown number of variables with unknown names to delete them.

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

4 Comments

I believe this will work for me. Let me try it out and see what happens and I will come back and check it off
I figured it out. it wanted push_back instead of append. Appreciate the help!
Oh jeez I'm sorry! I program a lot in Python and C++, and I mixed them up!
Why the dynamic allocation? You still have to delete these. Better to store values. If you really need to store pointers due to a polymorphic inheritance hierarchy, use std::unique_ptr.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.