I am trying to use a paymentList vector which has Cash, Cheque and Credit objects (which are derived classes of Payment) inside of the vector.
I declare the vector like this:
typedef std::vector<Payment*> ListOfPayments;
I add payments like this:
std::cout << "How would you like to pay?" << std::endl;
std::cout << "1. Cash" <<std::endl;
std::cout << "2. Credit"<<std::endl;
std::cout << "3. Cheque"<<std::endl;
std::cin >> choice;
while(choice < 1 || choice > 3)
{
std::cout<<"Please enter a correct number from 1 to 3"<<std::endl;
std::cin >> choice;
}
if(choice == 1)
{
paymentList->push_back(addCash(paymentId,orderId));
}
else if(choice == 2)
{
paymentList->push_back(addCredit(paymentId,orderId));
}
else
{
paymentList->push_back(addCheque(paymentId,orderId));
}
I now want to save this vector to a file. I have started a save function but I’m unsure where to go from here:
void savePayment(ListOfPayments *paymentList)
{
int method;
Cheque * pCheque = dynamic_cast<Cheque *>(paymentList->at(paymentList->size()-1));
Cash * pCash = dynamic_cast<Cash *>(paymentList->at(paymentList->size()-1));
Credit * pCredit = dynamic_cast<Credit *>(paymentList->at(paymentList->size()-1));
std::ofstream* save = new std::ofstream(); // creates a pointer to a new ofstream
save->open("Payments.txt"); //opens a text file called payments.
if (!save->is_open())
{
std::cout<<"The file is not open.";
}
else
{
*save << paymentList->size() << "\n";
ListOfPayments::iterator iter = paymentList->begin();
while(iter != paymentList->end()) //runs to end
{
method = (*iter)->getMethod();
*save << method << "\n";
if(method == 1)
{
pCash->saveCashPayments(save);
}
else if(method == 2)
{
pCredit->saveCreditPayments(save);
}
else
{
pCheque->saveChequePayments(save);
}
iter++;
}
save->close();
delete save;
}
}
It works if I save one type of payment, but as soon as I have two or more payments in the list I get a violation reading location error. I’m guessing it has to do with the type casts being wrong or something? In case I’m wrong here is an example of my save function that runs based on the method variable.
void Cash::saveCashPayments(std::ofstream* save)
{
*save << this->cashTendered << "\n";
*save << this->getId() << "\n";
*save << this->getAmount() << "\n";
*save << this->getOrderId() << "\n";
*save << this->getMethod() << "\n";
}
Any help would be appreciated 🙂
That is completely wrong approach.
A better approach would be runtime polymorphism. Declare a virtual function called
Savein base class and define it in each derived class.For example, if
Paymentis the base class, then do this:Then implement
Savein all derived classes.And then call
Saveusing pointer ofPayment*type.No need to pass
paymentby pointer; also don’t usenew std::ofstream.Read about Runtime Polymorphism in C++.