I am new to C++ and I am having difficulties with getting the vector.erase operation to work.
I have a database class as such:
template <class T> class Database
{
protected:
std::vector<T> m_database;
int m_counter;
public:
Database();
virtual ~Database();
// Accessor Methods.
T& getObject(int objectId);
bool exists(int objectId);
// Mutator Methods.
void add(T Object);
void del(int objectId);
};
and in practice, I am using the code as such:
Database<Account> accountDatabase;
Account
is a base class, with two derived classes, ChequingAccount
and SavingsAccount
.
I am inserting accounts, regardless of type (could be Account
, ChequingAccount
, SavingsAccount
) into this database using:
template <class T> void Database<T>::add(T object)
{
m_database.push_back(object);
++m_counter;
}
However, I am having issues with my delete operation. I am searching for a corresponding objectId
and then deleting it from the vector.
// Deletes the specified object from the database.
template <class T> void Database<T>::del(int objectId)
{
std::vector<T>& database = m_database;
typename std::vector<T>::iterator it = database.begin();
while (it != database.end()) {
if ((*it).getId() == objectId) {
it = database.erase(it);
} else {
++it;
}
}
}
Unfortunately the delete operation is not working at all. I am also having issues pulling a derived class from the database, as everything is being pulled out as an Account
type. I believe these two issues are tied to my noob C++ skills and bad design.
Any help would be greatly appreciated! Thanks!
EDIT
By not working, I mean the object is not deleted from the database. I apologize for any confusion.
The Account classes:
class Account
{
protected:
int m_id;
double m_balance;
std::string m_name, m_type;
public:
Account(int id, int userId, double balance = 0, std::string name = ""); // Constructor.
~Account(); // Destructor.
// Accessor Methods.
// This returns m_id AKA objectId
int getId() const;
}
class ChequingAccount: public Account
{
public:
ChequingAccount(int id, int userId, double balance, std::string name) : Account(id, userId, balance, name) {}
}
class SavingsAccount: public Account
{
public:
SavingsAccount(int id, int userId, double balance, std::string name) : Account(id, userId, balance, name) {}
}