Dynamically create N objects of a class based on user input?

Hello everybody!

I am new to this whole C++ thing and I have a (simple) question:

Is it somehow possible to "dynamically" create objects of a class?
So that N objects get created and named Event1, Event2, ... , EventN

Because I don't know if there have to be 5000 objects or 10000 objects or just a hand full of objects ...
It all depends on the "user input" ...

Here is the "pseudo-code" of what I want to do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  //Setting up the class of the objects
  class Event
    {
        public:
          int EventStartTimeInSeconds;
          int EventDurationInSeconds;
          string UserId;
          
    };

int MaximumNumberOfEvents;

cin >> MaximumNumberOfEvents;    //Actually this is in the "main" part somewhere

void SetUpAllTheObjects ()
  {
    //function that gets called to "make" all the objects
    for (int i = 0; i < MaximumNumberOfEvents; i++)
      {
        CreateNewObject()  //this is the part that I need help with
      }
  }



I have already found a post here that kind of asks the same question, but it doesn't quite make sense to me (http://www.cplusplus.com/forum/general/55496/).

It would be really great if somebody could help me with this.


(Otherwise I will just have to create a few arrays and make them have as many "entries" as I think could possibly be used ..)
Thanks for quick reply!

That looks just like what I need, thank you very much!

(When I first read "vector", I was still thinking about "euclidean vectors", so that's probably why it didn't make sense at first and I just thought "I don't want to do anything with those things, I want to create objects!" But that link that you posted mad things a lot clearer ...)
Learn C++ is IMO one of the best C++ tutorials sites available in English.

If you are looking for a reference on vectors: https://en.cppreference.com/w/cpp/container/vector

Since you want to create a container of objects you might want to look at std::vector's emplace() and emplace_back() member functions. insert() and push_back() create a temporary object before adding it to the std::vector. The other two functions "create in-place, no temporary." That can be a performance boost when dealing with custom objects.
(When I first read "vector", I was still thinking about "euclidean vectors")

Programming language theory draws more from abstract algebra & related fields:

If the domain of a 3D vector of real numbers is R^3 where R means "all the reals", the domain of a std::vector<int> is int^n where int means "all the possible ints" and n is the size of the vector.

This is the rationale for the name "vector". It's not particular to linear algebra.
Last edited on
Topic archived. No new replies allowed.