A
A
alex_deerk2016-06-23 18:54:17
C++ / C#
alex_deerk, 2016-06-23 18:54:17

Adding to a dynamic array of objects. Who will help?

I'm trying to add an object to an array, I seem to have used a similar one, but in that case it was not necessary to add an already existing object to the array. The program ends its work, on the third addition, or even on the second
. Please indicate the problem.
Here is the actual code:

void addPacient(Patient &p){
        if(p.getAge() < 18){
            throw AgeException();
        } else{
            addDays();
            ++count_places;
            if(places != nullptr){
                Patient *temp = places;
                places = new Patient[count_places];
                for(int i = 0; i < count_places - 1; i++){
                    places[i] = temp[i];
                }
                delete []temp;
                places[count_places - 1] = p;
                //cout << places[count_places - 1].getName() << endl;
            } else{
                places = &p;
                //cout << places->getName() << endl;
            }

        }
    }

And another question: So how do I pass an object to a method, can I change it? Is this the same as passing through a pointer?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2016-06-23
@alex_deerk

Tip #1: Use a std::vector instead of an array. It's really easier!
Tip number 2: use the vector from the Patient, that is, if possible, do not use pointers to store objects.
> So how do I pass an object to a method, will I be able to modify it? Is this the same as passing through a pointer?
Yes, references are essentially convenience pointers.
> and what would change if I passed through the pointer?
I would have to write extra dereferences.

D
Daniil Igorevich, 2016-06-23
@Petr_Anisimov

Yes, you can: you pass an object by reference, not by value

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question