user3812398
user3812398

Reputation: 1

Adding new objects to dynamic array

I am trying to write function to add objects name Hotel to dynamically allocated array. Problem is, while my code can add the first one, it fails to add anything further than that. Here is the code responsible for adding new objects.

void HotelReservationSystem::addHotel( const std::string name, const int numFloors, const int *numRooms)
{
    if ( hotelNum == 0 && hotels == NULL){
        hotels = new Hotel[1];
        Hotel hotelA ( name, numFloors, numRooms);
        hotels[0] = hotelA;
        hotelNum++;
        std::cout << "Hotel " << name << " is added." << std::endl;
        return;
    }
    for (int x = 0; x < hotelNum; x++){
        if ( name == hotels[x].getName())
            std::cout << "\n" << "Hotel " << name << " already exists." << std::endl;
            return;
    }
    Hotel* temp = new Hotel[hotelNum+1];
    for ( int x = 0; x < hotelNum; x++){
        temp[x] = hotels[x];
    }
    temp[hotelNum] = Hotel ( name, numFloors, numRooms);
    delete [] hotels;
    hotels = temp;
    hotelNum++;
    std::cout << "Hotel " << name << " is added." << std::endl;
}

So far i cant detect anything wrong with this code.

Upvotes: 0

Views: 128

Answers (2)

Logicrat
Logicrat

Reputation: 4468

You don't seem to have any declaration for the variable "hotels".

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110668

for (int x = 0; x < hotelNum; x++){
    if ( name == hotels[x].getName())
        std::cout << "\n" << "Hotel " << name << " already exists." << std::endl;
        return;
}

Here, the return is not part of the if statement. Your code will just return in the first iteration. You need to put braces around those two lines.

Of course, as the comments say, you shouldn't be doing memory management like this yourself. Use std::vector instead. Your function would become only a few lines.

Upvotes: 3

Related Questions