Reference to List of Objects invalid in Constructor - c++

I am working on some code to make a wallet to hold different currencies and this is my first time programming in c++ as a c programmer. Every time I make a new currency I want to add it to the list of valid Currencies that my wallet will be able to hold. To do this I make a currency class with a list that I want to add to every time a new currency is spawned. The error I get is error: no matching function for call to ‘std::__cxx11::list<Currency>::push_back(Currency*) CurrencyList.push_back(this);"\
Currency.h looks like:
#ifndef CURRENCY_H
#define CURRENCY_H
#include <string>
#include <list>
class Currency {
public:
//Instances of class
int id;
float max;
float left_over;
std::string coinName;
//Methods
float buyFrom(float amount);
float sellBack(float amount);
//constructor
Currency();
};
extern std::list<Currency> CurrencyList; //global list
#endif
Currency.c looks like
#include "currency.h"
#include <iostream>
Currency::Currency() {
Currency::id = 0;
std::cout << "Input name :" << std::endl;
std::cin >> Currency::coinName;
std::cout << "Input max :" << std::endl;
std::cin >> Currency::max;
Currency::left_over = Currency::max - 0;
CurrencyList.push_back(this);
}
float Currency::buyFrom(float amount) {
Currency::left_over-=amount;
std::cout << "Currency just lost :" << amount << "remaining is : " << Currency::left_over << std::endl;
}
float Currency::sellBack(float amount) {
Currency::left_over -= amount;
std::cout << "Currency just gained : " << amount << " remaining is : " << Currency::left_over << std::endl;;
}
The main is quiet simple it is only meant to spawn an object to test, that looks something like this.
Main.cpp
#include <iostream>
#include "wallet.h"
#include "currency.h"
int main(){
std::cout << "Hello World" << std::endl;
Currency currencyTest;
currencyTest.buyFrom(200.3);
}

Note that this is a pointer, but your list holds actual objects, not pointers.
So just dereference the pointer and you should be fine:
CurrencyList.push_back(*this);

Related

include "lvtocon.h", undefined reference to `operator<<(std::ostream&, char const*)

Working with C++ (Codeblocks 17.12 compiler), everytime program sees 'cout' in program.cpp i kept getting this message. Ideally need to create 'GoodAuto' object with three inserted variables (fuel_amount, double fuel_consumption and double best_speed); ability to change them with _change variables; ability to delete that 'GoodAuto' object.
Thanks in advance.
main.cpp
#include <iostream>
#include "program.h"
using namespace std;
int main(){
Auto GoodAuto(200, 5, 60);
}
program.cpp
#include "lvtocon.h"
#include <iostream>
#include "program.h"
using namespace std;
Auto::Auto(double fuel_amount, double fuel_consumption, double best_speed)
{
cout << "Enter fuel amount: " <<endl;
this->fuel_amount = (fuel_amount>=0)?fuel_amount: 10;
cout << "Enter fuel consumption for 100 km: " <<endl;
this->fuel_consumption = (fuel_consumption>0)?fuel_consumption: 1;
cout << "Enter optimal car speed: " <<endl;
this->best_speed = (best_speed>0)?best_speed: 120;
}
void Auto::Change(double fuel_amount_change, double fuel_consumption_change, double best_speed_change)
{
if (fuel_amount+fuel_amount_change>0) this->fuel_amount += fuel_amount_change; else fuel_amount = 0;
if (fuel_consumption+fuel_consumption_change>0) this->fuel_consumption += fuel_consumption_change; else fuel_consumption = 1;
if(best_speed + best_speed_change>0) this->best_speed += best_speed_change; else best_speed = 120;
}
void Auto::Print(){
cout << "Fuel amount = " << fuel_amount << " l."<< endl;
cout << "Fuel consumption for 100 km = " << fuel_consumption << " l/stunda." <<endl;
cout << "Auto optimal speed = " << best_speed <<" km/stunda."<<endl;
}
program.h
class Auto
{
private:
double fuel_amount;
double fuel_consumption;
double best_speed;
public:
Auto(double fuel_amount, double fuel_consumption, double best_speed);
~Auto();
void Change(double fuel_amount_change, double fuel_consumption_change, double best_speed_change);
void Print();
};
In my case, the problem was that I did not include all the necessary libraries in the project.
For latvian language support i used library lvtocon.h and lvtocon.cpp, but since my program has include and didn't see the file, it would not run succesfully.
After adding all the necessary files to the project it compiled succesfully.
You don't seem to implement your destructor. Please try to include the implementation of ~A() {}.

Getting Today's Date into variable

i have that c++ project. i want to get today's date to compare it with a saved date in my files. i already searched but all i found is i can output it on the console but that isn't what i want. is it possible?
#include <iostream>
#include <cmath>
#include <string>
#include <chrono>
#include <ctime>
using namespace std;
static double interset = .05;
class Account{
public:
string ID;
double Balance;
void Deposit(double bal){
Balance += bal;
}
void Withdraw(double bal){
if (bal > Balance){
cout << "Please check the entered amount" << endl;
}
else{
Balance -= bal;
}
}
void BalanceInqu(){
cout << "Your Current Balance Is\t" << Balance << endl;
}
};
class SavingAccount : public Account{
public:
void intersetRate(){
\\i want to put here a function that calculates the interest rate of an client depending on his account creation date
}
};
Edit: i want to get the date to store it into variable and compare it with other dates
If you have the date or time for now, you just need to subtract the start time and the transform the result into days, if that's not already the case. So this means that you don't need to get the actual date for today.
The time_since_epoch can be enough, because you just want to have the difference between 2 timestamps.
#include <iostream>
#include <chrono>
#include <ctime>
tm chronoTPtoTM(const std::chrono::system_clock::time_point& tp) {
time_t aux = std::chrono::system_clock::to_time_t(tp);
return *localtime(&aux);
}
int main(int argc, char** argv) {
std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
tm local_time = chronoTPtoTM(t);
std::cout << "Now is "
<< local_time.tm_year+1900 << "/"
<< local_time.tm_mon+1 << "/"
<< local_time.tm_mday << " "
<< local_time.tm_hour << "h"
<< local_time.tm_min << "m"
<< local_time.tm_sec << "s"
<< std::endl;
return 0;
}
This is a simple working example of the usage of the std::chrono::system_clock::time_point. This class even has comparator operators defined so you can compare two of these easily with <, >, <=, >=, "==" and "!=".
In the example, I've included a way to convert the time_point into a human readable format.

Undefined Reference c++ lost

#include "assert.h"; // for some reason assert wouldn't work on my compiler without this
#include <iostream>
#include <string>
#include <limits> // This is helpful for inputting values. Otherwise, funny stuff happens
using namespace std;
class Product
{
public:
Product();
Product(string the_name, int the_price, int number_of);
string return_name();
void reduce_amount();
void print_data() const;
private:
string prod_name; // name of your product
int price_in_cents; // it's price in cents
int amount; // the number of the product that you have
};
Product::Product()
{
prod_name = "NULL_NAME: NEED DATA";
price_in_cents = 0;
}
Product::Product(string the_name, int the_price, int number_of)
{
assert(the_price>0);
assert(number_of>0);
assert(number_of<21);
assert(prod_name !="NULL_NAME: NEED DATA");
prod_name = the_name;
price_in_cents = the_price;
amount = number_of;
}
void Product::print_data() const
{
cout<<prod_name << endl;
cout<<"The price in cents is: " <<price_in_cents<< endl;
cout<< "Amount left: " << " " << amount << endl;
}
void Product::reduce_amount()
{
amount = amount -1;
}
string Product::return_name()
{
return prod_name;
}
class Vending_Machine
{
public:
Vending_Machine();
void empty_coins();
void print_vend_stats();
void add_product();
Product buy_product();
private:
int income_in_cents;
Product product1();
Product product2();
Product product3();
Product product4();
Product product5();
};
void Vending_Machine::empty_coins()
{
cout << "The total amount of money earned today is " << income_in_cents << " cents" << endl;
income_in_cents = 0;
cout << "All the coins have been withdrawn. The balance is now zero." << endl;
}
void Vending_Machine::print_vend_stats()
{
cout<< "Total income thus far: " << income_in_cents << endl;
if (product1().return_name() != "NULL_NAME: NEED DATA")
{
//stuff happens
}
}
int main()
{
return 0;
}
So, I'm not sure if I did all the identation correctly, but I'm having a problem with the boolean statement in vending machine print_vend_stats() function. It's saying I am making an undefined fereence to product1(). What does this mean?
When you declare
Product product1();
you declare a member function, the parentheses is what makes it a function.
If you drop the parentheses
Product product1;
you declare a member variable, an actual instance of the Product class.
Another example, you wouldn't write e.g.
int income_in_cents();
do declare income_in_cents as a variable, now would you?
It doesn't matter if the type is a primitive type like int, or a class like Product, Member variables are declared like normal variables like you do anywhere else.

Code keeps displaying variable even after it is deleted

I am still new to c++ and just started to learn about classes and OOP. I have been practicing trying to make classes out of any item I can think of, so I made a phone class. Code is below. The problem is no matter what number I give it, it displays the same WRONG number everytime. The crazy thing is in the beginning I had given the phone class a variable to store its own number and gave the class instance its own number. That number is the number it keeps wanting to "call". Even after going back several times and making sure I wasn't calling the wring variable I completely deleted the variable and the code still displays the same number. The number is 214-748-3647. Makes me feel like my computer is haunted. Could anyone help?
CODE DOESN'T ACTUALLY MAKE ANY SORT OF PHONE CALL OR ANY CONNECTION WHAT SO EVER
PHONE CLASS HEADER
#ifndef PHONE_H_INCLUDED
#define PHONE_H_INCLUDED
#include <string>
using namespace std;
class Phone{
public:
string Brand;
int Serial;
string CellId;
void Call();
private:
void Dial(int NumberToDial);
void EndCall();
};
#endif // PHONE_H_INCLUDED
PHONE SOURCE CODE
#include <iostream>
#include <string>
#include <sstream>
#include "phone.h"
using namespace std;
void Phone::Call(){
string UserInput = "0";
int NumberToCall = 0;
cout << "What number would you like to call?" << endl << endl;
getline(cin, UserInput);
if(UserInput.length() != 10){
cout << endl << "invalid digits" << endl;
Call();
}
else{
stringstream(UserInput) >> NumberToCall;
Dial(NumberToCall);
}
}
void Phone::Dial(int NumberToDial = 0){
ostringstream converter;
string Number;
converter << NumberToDial;
Number = converter.str();
cout << "Dialing ";
for(int i=0;i<10;i++){
cout << Number[i];
if(i==2){
cout << "-";
}
if(i==5){
cout << "-";
}
}
cout << endl << endl << "Press any key to end the call..." << endl << endl;
cin.get();
EndCall();
}
void Phone::EndCall(){
cout << "Call ended." << endl << endl;
}
Aaaaannnnd my MAIN
#include <iostream>
#include <cstdlib>
#include "phone.h"
using namespace std;
int main()
{
Phone MyPhone;
MyPhone.Brand = "iPhone 5";
MyPhone.CellId = "F2D9G3A2";
MyPhone.Serial = 1411512;
MyPhone.Call();
return 0;
}
This is a very simple answer. You're code and logic is fine. The error occurs because you convert the std::string which holds the phone number to an integer. This is a problem because a typical 10 digit phone number is too big to fit inside the int type. Have a look here to see the min and max numbers you can fit in different types: http://www.cplusplus.com/reference/climits/
Look at this line here actually.
Maximum value for an object of type long int: 2147483647 (231-1) or greater
Funny how the max value is that mysterious phone number.

Storing a objects derived from an abstract base class with maps in a vector array of base class pointers

I'm writing a program that uses OOP to store student records. At the moment I only have two classes, one for each individual course module called 'Courses', and one ( well two if you count the abstract base class) for the type of degree programme called 'Physics' derived from the 'Records' base class.
I'm using two maps in the program. One to store the individual courses for each individual record and sort them by course code, and one to store all the records and sort them by ID numbers.
I planned on having the user input all student information, including codes, storing this in a vector (named 'prec' in the code), then pushing the vector elements into the map used to store all the records. The code is far from finished, I was just attempting to run it to see if I was on the right track.
The code builds without any errors, but when I attempt to run it, it comes up with the error message: " Debug assertion failed: expression vector subscript out of range". I feel this may have something to do with the way I am using individual vector elements to call my functions to store courses in the maps but I cant quite get it, any help would be much appreciated!
Here are my files:
header file:
#ifndef MY_CLASS_H // Pre-processor directives to prevent multiple definition
#define MY_CLASS_h
#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <fstream>
using std::string;
using std::ostream;
using std::map;
using std::cout;
using std::endl;
using std::cin;
namespace student_record // Defines the namespace student_record in which the classes are defined
{
class Course { /* Create class Course for individual courses, is this better than incorporating
all the data separately into the Record class below? Class contains course name, mark achieved and mark weight and course ID */
protected:
string course_name;
double course_mark;
int course_Id;
public:
Course() {course_name= "Null"; // Default constructor for null course
course_mark=0;
}
Course(string course_namein, double course_markin, int course_Idin) {course_name=course_namein; // Parametrized constructor to create course with set name, mark, weight and course ID
course_mark=course_markin;
course_Id=course_Idin;}
~Course() {course_name.erase(0,course_name.size());} // Destructor to delete the course name
// Access functions to get name, mark and weight //
double getmark() const {return course_mark;}
string getname() const {return course_name;}
int getid() const {return course_Id;}
friend ostream & operator << (ostream &os, const Course &c); // Friend function to overload the insertion operator for courses
};
class Record
{ // Create class Record as abstract base class for all inherited degree classes
protected:
string student_name;
int studentid;
int years;
public:
Record() {student_name="Casper";
studentid=0;
years=0;} // Default constructor for class Record, produces empty record
Record(string name, int number, int time) {student_name=name;
studentid=number;
years=time;} // Parametrized constructor for class Record
~Record() {student_name.erase(0, student_name.size());} // Destructor to delete the student name
virtual int getid()const=0;
virtual int getyears()const=0;
virtual void show_record()const=0;
virtual void print_record(string *filename)const=0;
virtual void degree_class()const=0;
virtual void insert_class()=0;
/* Virtual functions defined to be used in the derived classes (subjects ie, Physics, stamp collecting, etc...)
Thus the base class Record is abstract*/
};
class Physics: public Record
{
private:
string degree_name;
typedef map <int, Course> course_map;
course_map modules;
void searchdatabase (course_map &courses, int coursecode)const; // Uses iterator to search map for corresponding course to inputted key ( remember to move to function definitions)
string get_name (const int i, course_map &temp) const{ return temp[i].getname();}
double get_mark(const int i, course_map &temp)const{ return temp[i].getmark();} // Functions to return the mark, weight and name of a given course corresponding to inputed course code
int getid()const{return studentid;}
int getyears()const{return years;}
void show_record()const;
void print_record( string *filename) const;
void degree_class()const;
void insert_class();
// Function to insert record into map
public:
Physics():Record(){degree_name= "Physics ";}
Physics(string name,int Id, int time):Record( name, Id, time){degree_name= "Physics";}
~Physics() {degree_name.erase(0, degree_name.size());}
};
}
#endif
function definitions:
#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <fstream>
#include <vector>
#include "Database_header.h"
using namespace std;
using namespace student_record;
ostream & student_record::operator<< (ostream &os, const Course &c)
{
os<< "Course code" << c.course_Id << " \n Course name: " <<c.course_name << " \n Mark " << c.course_mark <<endl;
return os;
}
// Function to insert classes //
void Physics::insert_class()
{
int courseid;
string coursename;
double mark;
cout << " Enter course code " << endl;
cin >> courseid;
cout << " \n Enter course name " << endl;
cin >> coursename;
cout << " \n Enter mark achieved " << endl;
cin >> mark;
Course temp (coursename, mark, courseid);
modules.insert(pair<int, Course>(courseid, temp));
}
void Physics::searchdatabase(course_map &courses, int coursecode) const // Function to search for specific course mark based on course code, need to modify this!!!!
//takes in a map as its argument, although i suppose can use student.modules?
{
course_map::iterator coursesIter;
coursesIter=courses.find(coursecode);
if(coursesIter != courses.end())
{
cout << " Course Code " <<
coursecode << " corresponds to " <<
coursesIter ->second << endl;
}
else { cout << " Sorry, course not found " << endl; }
}
void Physics::print_record( string *filename) const // Function for printing record to the file
{
ofstream myoutputfile;
myoutputfile.open(*filename,ios::app);
if(!myoutputfile.good())
{
// Print error message and exit
cerr<<"Error: file could not be opened"<<endl;
}
if(myoutputfile.good())
{
myoutputfile << "Student name: " << student_name << endl
<< "\n Student ID: " << studentid << endl
<< "\n Year: " << years << endl;
course_map::iterator modulesiter; // Iterator to print out courses using overloaded << function (I think?)
for(modulesiter==modules.begin();modulesiter!=modules.end();modulesiter++)
{
myoutputfile<<modulesiter->second << endl;
}
}
}
void Physics::show_record() const // Function for showing specific student record on screen ( with iterator for map of courses)
{
cout << "Student name: " << student_name;
cout << "\n Student ID: " << studentid;
cout << "\n Years on course: " << years;
cout << "\n Courses and grades: ";
course_map::iterator modulesiter; // Iterator to print out courses using overloaded << function (I think?)
for(modulesiter==modules.begin();modulesiter!=modules.end();modulesiter++)
{
cout<<modulesiter->second << endl;
}
}
void Physics::degree_class()const
{
double temp;
vector<double> dynarr; // Create a vector array to store the grades extracted from the course map for each student
course_map::iterator modulesiter;
for(modulesiter==modules.begin();modulesiter!=modules.end();modulesiter++) // Iterate through map and push values into each vector
{
Course ghost;
ghost=modulesiter->second;
dynarr.push_back(ghost.getmark());
}
double sum(0);
for(int i(0);i<=dynarr.size();i++)
{
sum+=dynarr[i];
}
temp=sum/dynarr.size();
if( temp>=40 && temp <=49.9)
{
cout << "The student has achieved a 3rd class degree with an average of: \n "
<< temp;
}
else if( temp>=50 && temp <=59.9)
{
cout << "The student has achieved a 2:2 degree with an average of: \n "
<< temp;
}
else if( temp>=60 && temp <=69.9)
{
cout << "The student has achieved a 2:1 degree with an average of: \n "
<< temp;
}
else if( temp>=70)
{
cout << "The student has achieved a 1st class degree with an average of: \n "
<< temp;
}
else { cout << "The student has failed the degree " << endl;}
}
and main cpp file:
#include <iostream>
#include <utility>
#include <map>
#include <iomanip>
#include <vector>
#include "Database_header.h"
#include <fstream>
using namespace std;
using namespace student_record;
void main()
{
// Create map to store students with ID keys //
string full_name;
int id;
int time;
string degree_name;
vector<Record*> prec;
// Vector of base class pointers to store all the different records first. No need to specify length as it is a vector! (Advantage over dynamic array?)
char student_test('y'); // Condition for adding students to the record //
int q(0);
while (student_test=='y' || student_test=='Y')
{
// Counter for while loop
cout<< " \n Please enter the student name " << endl;
getline(cin, full_name);
// Enter student name, check it is a string? //
cout<< "\n Please enter student ID " << endl;
cin >> id;
// Check if not integer or number, if not need error message //
cout << "\n Please enter the number of years on the course " << endl;
cin >> time;
// Check if not integer or number, if not need error message //
cout<< "\n Please enter degree type " << endl;
cin>>degree_name;
if(degree_name=="Physics" || degree_name=="physics") // create object of appropriate derived class ( Physics, Chem, Maths, Bio)
{
prec.push_back(new Physics(full_name, id, time));
}
char class_test('y'); // test condition for class insertion loop
while(class_test=='y') // Add courses+marks into course map
{
cout << " \n Add classes to student record " << endl;
prec[q]->insert_class();
cout << " \n Add another class? Y/N" << endl;
cin>>class_test;
}
cout << "Enter another student? Y/N " << endl;
cin >> student_test;
if(student_test=='N' && student_test=='n')
{
cout << "\n Thank you for using the student database, Goodbye !" << endl;
}
q++; // increment counter, to keep track of of vectors of base class pointers, and also be able to output number of students
}
// Next insert all records into map //
typedef map<int, Record*> studentlist;
studentlist studentmap;
for(int i(0); i<=prec.size(); i++)
{
studentmap.insert(pair<int, Record*> (prec[i]->getid(), prec[i]));
}
}
Thanks so much!
for(int i(0); i<=prec.size(); i++)
{
studentmap.insert(pair<int, Record*> (prec[i]->getid(), prec[i]));
}
Should be i < prec.size() instead of <=