I am a c++ beginner. I was practicing how to work with class and header files. The program manages Rents of a building. It has a Rent
class and a Floor
class. Here're some definitions of those classes.
rent.cpp (Copied important functions only)
Manages information about Floor
s and has vector<Floor> paid_by_floors;
property.
#include "rent.hh"
void Rent::set_floor_count(int count){
this->paid_per_floors.reserve(count);
this->paid_per_floors.resize(count);
}
void Rent::set_floor(int index, Floor floor){
this->paid_per_floors[index] = floor;
}
Floor Rent::get_floor(int index){
return this->paid_per_floors[index];
}
floor.cpp (Copied important functions only)
Manages information about rooms and has vector<Floor> paid_by_rooms;
property.
#include "floor.hh"
void Floor::set_room_count(int count){
this->paid_per_rooms.resize(count, 0);
}
int Floor::get_room_amount(int index){
return this->paid_per_rooms[index];
}
void Floor::set_room_amount(int index, int amount){
this->paid_per_rooms.push_back(amount);
// Tried with paid_per_rooms[index] = amount;
}
main.cpp
int main(int argc, char const *argv[])
{
Rent m_rent(5);
cout << m_rent.get_floor_count() << endl; // stdout line:1
m_rent.set_floor_count(2);
cout << m_rent.get_floor_count() << endl; // stdout line:2 (correct)
m_rent.get_floor(0).set_room_count(5);
cout << m_rent.get_floor(0).get_room_count() << endl; // stdout lines:3 (incorrect)
m_rent.get_floor(0).set_room_amount(0, 100);
m_rent.get_floor(0).get_room_amount(0); // stdout line:4 (seg fault)
return 0;
}
And output on stdout
.
5
2
0
Segmentation fault (core dumped)
As you can see When I change the size of the paid_per_floors
vector. It works. But, it does not work with paid_per_rooms
. Also, it returns a segmentation fault which stands for OutOfBound
. How should I fix it?
Did Some Research Before
Searched on google about this problem with queries like vector resize does not work, vector resize does not increase size. The answers were to use push_back
without array indexing like vec[0]
. In set_room_count
function I have also used reserve
before resize
. But, the problem didn't get fixed.