i'm assuming this is going to be a really simple fix but i've been staring at this code for so long my brains turned to mush.
For background, we've had to create a bank account program. I have a Account class and a Person class. My issue lies in the Person class. When a person gets instantiated it should automatically create an account object and push it into a vector. I also have a method that lets me add another account or delete one.
My issue is, when in my main class, the vector is coming up as 0 when using the v.size() method. I'll paste my code below, i'm very new to C++ and only just really been introduced to pointers so bare that in mind.
Person.cpp
#include "pch.h"
#include "Person.h"
#include <iostream>
using namespace std;
Person::Person()
{
Account acc1;
account.push_back(acc1);
}
void Person::newAccount() {
Account acc1;
account.push_back(acc1);
}
void Person::closeAccount(int index) {
cout << "Which account would you like to close?" << endl;
cin >> index;
account.erase(account.begin() + index);
}
Person::~Person()
{
}
Person.h
#pragma once
#include "Account.h"
#include <vector>
using namespace std;
class Person
{
public:
Person();
void newAccount();
void closeAccount(int index);
~Person();
private:
vector <Account> account;
};
Then in the main class I have:
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <vector>
#include "Account.h"
#include "Person.h"
using namespace std;
int amount;
int years;
int balance;
vector <Account> accounts;
int main()
{
Person p;
Account a;
p.newAccount();
cout << accounts.size() << endl;
I left out the rest of the main class as that has nothing to do with this error but will post if needed.
Any help would be appreciated
The issue is that you are sampling the size of a global variable called
vector <Account> accounts;
This is not the same as the member variable you declared in your Person class called
vector <Account> account;
declared in your person class below:
class Person
{
public:
Person();
void newAccount();
void closeAccount(int index);
~Person();
private:
vector <Account> account;
};
These are two separate objects and your account appending is happening to your member variable within your Person Class. Change the output statement to report the size of the account vector of a Person instance through a function since the vector is private and it will report the correct size.
class Person
{
public:
Person();
void newAccount();
void closeAccount(int index);
~Person();
inline int GetAccountNum() const { return account.size(); }
private:
vector <Account> account;
};
int main()
{
Person p;
p.newAccount();
cout << p.GetAccountNum() << endl;
}
One popular coding convention C++ programmers use is to prefix member variables with m_ or m to avoid these kind of easy mistakes. It also can help to change the name of your vector to something other than just the plural form of the object.
Lastly, the Account object a, you are creating on the stack in the main function is not being used. This would produce a warning in most IDE's. If your intention was to add the account you created on the stack to your Person object's account vector, then you should create a function that accepts an account by reference and adds it to the member variable account vector for the Person object.
Follow the convention I listed above and it should help you avoid this mistakes in the future.
Related
This question already has answers here:
How do I write setters and getters for an array? (c++)
(3 answers)
Closed 3 years ago.
I'm trying to represent a Course with Students. The Students have information about their first and last names, age... And the Courses have a name and an array of 3 Students.
I'm getting an error when I try to define the getters and setters for the array.
Error (active) E0415 no suitable constructor exists to convert from "Student [3]" to "Student"
Error (active) E0137 expression must be a modifiable lvalue
Course.h
#pragma once
#include "Student.h"
#include "Teacher.h"
class Course
{
private:
string name;
Student students[3];
Teacher teacher;
public:
Course();
~Course();
void setName(string name);
string getName();
void setStudents(Student students[3]);
[3] Student getStudents();
};
Course.cpp
#include <iostream>
#include "Course.h"
#include "Student.h"
#include "Teacher.h"
using namespace std;
Course::Course() {}
Course::~Course()
{
}
void Course::setName(string name)
{
this->name = name;
}
string Course::getName()
{
return this->name;
}
void Course::setStudents(Student students[3])
{
/*for (int i = 0; i < 3; i++) {
this->students[i] = students[i];
}*/
//This way the set works
this->students = students;
}
[3]Student Course::getStudents()
{
return this->students;
}
I expect the output of the get to be the array of students.
A C style array cannot be copied, cannot be automatically assigned, and cannot be returned from a function.
Thankfully, the C++ standard library provides a thin wrapper class over C style arrays which implement all these operations. It’s called std::array and it can be used exactly like you’re trying to use C-style arrays.
#pragma once
#include "Student.h"
#include "Teacher.h"
#include <array>
class Course
{
private:
string name;
std::array<Student, 3> students;
Teacher teacher;
public:
Course();
~Course();
void setName(string name);
string getName();
void setStudents(std::array<Student, 3> students);
std::array<Student, 3> getStudents();
};
I am really stuck with the problem here.
So basically I have a Stock class and a BuyOrder class.The BuyOrder class takes the Stock class as a member so it knows which stock to buy. When the stock is created, it takes in a company name and initializes with random prices. Then I can create a buy order takes in bidPrice,bidQuantity,Stock arguments.
In the main I want to create an array of BuyOrder to store the orders. Then every time the user created an order, the order can be stored.
My first approach is to declare BuyOrder buyList[100]. This way every time the user created an order, I can use the set functions to set each buyList[i] and then increment i. However, when I declare BuyOrder buyList[100]in main. It says No matching constructor for initialization of 'BuyStock buyList[100]' I went back to BuyOrder.cpp try to add a default constructor BuyOrder::BuyOrder(){} then it shows the error:Constructor for 'BuyOder'must explicitly initialize the reference member 'buyStock'.
I don't know how to proceed from here. Very much appreciated.
Below is part of BuyOrder.cpp since it way too long and the rest part are just function definitions.
BuyOrder::BuyOrder{double price, int quantity, Stock &s)
:buyPrice{price},
buyQuantity{quantity},
buyStock{s}{}
void BuyOrder::setBuyStock(Stock stock){
buyStock = stock;
}
void BuyOrder::setBuyOrderPrice(double price) {
buyPrice = price;
}
void BuyOrder::setBuyOrderQuantity(int quantity) {
buyQuantity = quantity;
Below is BuyOrder.h
#ifndef BUYORDER_H
#define BUYORDER_H
#include <ctime>
#include<iostream>
#include "Stock.h"
class BuyOrder {
friend void getCurrentTime();
public:
BuyOrder(double , int , Stock & );
void setBuyStock(Stock);
void setBuyOrderPrice(double price);
void setBuyOrderQuantity(int quantity);
double getBuyOrderPrice();
int getBuyOrderQuantity();
void placeBuyOrder();
void checkExcute();
void modifyBuyOrder();
void cancelBuyOrder();
double getHighestBidPrice();
int getHighestBidPriceQuantity();
double getLowestBidPrice();
int getLowestBidPriceQuantity();
private:
double buyPrice;
int buyQuantity;
bool excute = false;
Stock &buyStock;
time_t t;
};
#endif
This is the Stock.h
#ifndef STOCK_H
#define STOCK_H
#include <vector>
#include <string>
using namespace std;
class Stock {
friend void getCurrentTime();
public:
Stock();
Stock(string nameOfCompany);
int getBidTerms();
int getAskTerms();
void printStockInfo();
void initialize();
void sortBid();
void sortAsk();
string nameOfCompany;
string currentTime;
vector<double> askPrice;
vector<int> askQuantity;
vector<double> bidPrice;
vector<int> bidQuantity;
int bidTerm;
int askTerm;
};
#endif
and this is Stock.cpp excluding the long function definitions
#include "Stock.h"
#include <iostream>
#include <vector>
#include <time.h>
#include <iomanip>
#include <ctime>
#include <random>
#pragma warning(disable : 4996)
using namespace std;
void getCurrentTime() {
time_t rawTime;
struct tm * timeinfo;
time(&rawTime);
timeinfo = localtime(&rawTime);
cout << asctime(timeinfo);
}
Stock::Stock(){}
Stock::Stock(string companyName) :nameOfCompany{ companyName } {
initialize();
sortBid();
sortAsk();
}
Because your BuyOrder class (which you don't show us, and should) contains a reference member (Stock &buyStock;), you have to set that reference to something within any constructor for the class. This means that you can't normally use a default constructor, as that does not initialize the reference.
Possible solutions include changing buyStock to not be a reference, changing it to be a pointer (which can be nulled out for those cases where it doesn't represent an order yet), or changing containers from a fixed size array to something that can be resized, like a vector.
I'm trying to create a vector which will store objects. I have added to the header file of the class as a private data member.
I am trying to initialize this vector as being empty (so that I can add objects to it later on in the program) but when I compile this program to test, this error is returned:
...error: '_bookingVector' was not declared in this scope|
I think the problem is with my initialization list on my default constructor(_bookingVector is obviously the vector):
Schedule::Schedule() : _bookingVector()
{ }
Is my syntax wrong? Or are vectors initialized differently?
Here is my code:
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "Booking.h"
#include <vector>
using namespace std;
class Schedule
{
public:
Schedule();
void AddBooking(int bday, int btime, int btrainer, int bid);
void RemoveBooking(int bday, int btime);
void DisplaySchedule();
void DisplayAvailableTimeSlots();
//For Testing
void DisplayDebug();
private:
vector<Booking> _bookingVector;
};
#endif // SCHEDULE_H
Schedule.cpp
#include "Schedule.h"
#include "Booking.h"
#include <vector>
#include <iostream>
Schedule::Schedule() : _bookingVector()
{ }
void AddBooking(int bday, int btime, int btrainer, int bid){
Booking bookingObject(bday, btime, btrainer, bid);
_bookingVector.push_back(bookingObject);
}
void DisplayDebug(){
for(int i = 0; i < _bookingVector.size(); ++i){
cout << _bookingVecotr[i] << endl;
}
}
I'm very eager to learn what I'm doing wrong and fix it.
The issue is not with the constructor, which looks fine if unnecessary1. The issue is that you have defined AddBooking and DisplayDebug as non-member functions, but these should be members in order to access other members of the class.
Modify the definitions to be in the scope of the Schedule class thus:
void Schedule::AddBooking(int bday, int btime, int btrainer, int bid) { ...
^^^^^^^^^^
void Schedule::DisplayDebug(){ ...
^^^^^^^^^^
Also, don't say using namespace std in a header file (I'd go further and say don't say it anywhere but there isn't universal agreement on that.)
1 Your default constructor does not do anything that the compiler-generated one wouldn't do. You can safely remove it.
I've spent quite a few hours researching and trying to figure out why I'm getting this error. Basically the three files that have to do with the inheriting are CollegeMember.h, Employee.h, and EmpAcademicRecord.h. Employee. is inheriting from CollegeMember.h and EmpAcademicRecord.h is inheriting from Employee.h. Like this CollegeMember <- Employee <- EmpAcademicRecord. The error occurs in EmpAcademicRecord.h. Heres the three files.
CollegeMember.h
#include <cstdlib>
#include <iostream>
#include<ctype.h>
#include<string.h>
#include "Employee.h"
#include "Student.h"
using namespace std;
// ****************************************************************************
// Class Definitions follow
typedef char* String;
// The CollegeMember class
class CollegeMember
{
protected:
int ID_Number;
string FirstName, LastName;
string AddressLine1, AddressLine2, StateProv, Zip;
string Telephone;
string E_Mail;
string answer, answer2, answer3, answer4;//used as sort of booleans for use with validation
// member functions
public:
CollegeMember ( ); // constructor
CollegeMember(const CollegeMember&); //overloaded constructor
void Modify (CollegeMember Member);
void InputData(int x);
string Summary ( ); //summary
string PrintMe(); //fully describes
}; // End of CollegeMember class declaration
Employee.h
#include <cstdlib>
#include <iostream>
#include<ctype.h>
#include<string.h>
#include "EmpAcademicRecord.h"
#include "EmpEmploymentHistory.h"
#include "EmpExtraCurricular.h"
#include "EmpPersonalInfo.h"
#include "EmpPublicationLog.h"
using namespace std;
// ****************************************************************************
// Class Definitions follow
typedef char* String;
// The Employee Class
class Employee: protected CollegeMember
{
float Salary;
protected:
string Department, JobTitle;
// Member Functions
public:
Employee ( ); // constructor
void Modify (Employee ThisEmp);
void InputData(int x);
void SetSalary (float Sal) // Specified as an in-line function
{ Salary = Sal;}
float GetSalary ( ) {return Salary;} // Specified as an in-line function
string Summary ( ); //summary
string PrintMe(); //fully describes
}; // End of Employee class declaration
EmpAcademicRecord.h
#include <iostream>
#include <cstdlib>
#include<ctype.h>
#include<string.h>
using namespace std;
typedef char* String;
class EmpAcademicRecord: protected Employee{ //error occurs on this line
protected:
int ReferenceNumber;
string Institution;
string Award;
string start;
string end;
public:
EmpAcademicRecord();
void InputData (int x);
void Modify(EmpAcademicRecord ThisRec);
void Summary();
};
Any help with this would be greatly appreciated.
That sort of error is usually caused by the type not being defined when you try to use it.
In this case, it appears that you may have included EmpAcademicRecord.h without having first included Employee.h (the includes at the top of the former do not show the latter).
In other words, at the point where the compiler sees:
class EmpAcademicRecord: protected Employee { //error occurs on this line
it has no idea what the Employee class is.
It may be a simple matter of adding:
#include "Employee.h"
to the top of that file, it's a little difficult to be certain since we don't have the code files. In any case, it's certainly a good first step.
Since you have EmpAcademicRecord.h being included by Employee.h, that will probably result in an infinite recursion.
You could fix that with include guards, but I can't see why you need that particulat inclusion. EmpAcademicRecord depends on Employee, not the other way around.
I'm trying to simply use a vector within one of my classes. When trying to access the vector it tells me that it's undefined (but I've defined it in my header).
I have two classes, Person and Dog. A person can own one or more dogs so I want to add each dog a person owns into an array. This should be real simple so this problem is really starting to get to me. Here's some code:
The class Person.cpp:
#include "Person.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
Person::Person(string name, string address, int age)
:name(name),
address(address),
age(age)
{}
int Person::getAge(){
return age;
}
std::string Person::getDogInfo(int index){
}
void Person::addDog(string dogName, string breed){
dogCollection.push_back(Dog(dogName, breed));
}
std::vector<Dog> getDogs(){
return dogCollection; //dogCollection undefined error here
}
And here's Person.h:
#ifndef Person_H
#define Person_H
#include <vector>
#include "Dog.h"
using namespace std;
class Person{
public:
Person(string name, string address, int age);
string getName(){return name};
string getAddress(){return address};
void addDog(string dogName, string breed);
string getDogInfo(int index);
std::vector<Dog> getDogs();
int getAge();
private:
string name;
string address;
int age;
std::vector<Dog> dogCollection;
};
#endif
If you want to have a look at my dog classes I'll paste them as well:
Dog.cpp:
#include "stdafx.h"
#include <iostream>
#include "dog.h"
Dog::Dog(string dogName, string breed)
:dogName(dogName),
breed(breed){}
std::string Dog::Dog.getDogName(){
return dogName;
}
std::string Dog::Dog.getBreed(){
return breed;
}
and Dog.h:
#ifndef Dog_H
#define Dog_H
#include <iostream>
using namespace std;
class Dog{
public:
Dog(std::string dogName, std::string breed);
std::string getDogName();
std::string getBreed();
private:
std::string dogName;
std::string breed;
};
#endif
Also, I just want to add that this is no homework. I'm used to java and I'm only trying to learn some C++ since I need it for future work.
EDIT: Updated the code
std::vector<Dog> dogCollection; // here im defining dogCollection, no error here!
There actually is an problem here - class Dog isn't known to the compiler at this point.
You can solve this by either including Dog.h before Person.h in Person.cpp, or better add an #include "Dog.h" at the top of Person.h.
This is incorrect (and unrequired):
dogCollection = new std::vector<Dog>; // Remove this line.
as dogCollection is not a std::vector<Dog>*.
This is also incorrect:
void Person::addDog(string dogName, string breed){
Dog *newDog = new Dog(dogName, breed);
dogCollection.push_back(newDog);
}
as dogCollection contains Dog instances, not Dog*. Change to:
void Person::addDog(string dogName, string breed){
dogCollection.push_back(Dog(dogName, breed));
}
There is a problem with all of constructors:
Person::Person(string name, string address, int age){
name=name;
address=address;
age=age;
}
This is assigning the argument name to itself: it is not assigning to the member name. Same for address and age and similarly for the constructors of the other classes. Use initializer list:
Person::Person(string name, string address, int age) :
name(name),
address(address),
age(age)
{}
This method does not return a std::string:
string Person::getDogInfo(int index){
}
EDIT:
Missing class qualifier:
std::vector<Dog> getDogs(){
return dogCollection; //dogCollection undefined error here
}
means this is just a free function, with no association to class Person and therefore no access to dogCollection.
Change to:
std::vector<Dog> Person::getDogs(){
return dogCollection;
}
There are several problems with your code, and most of the other answers have pointed them out - mostly regarding the use of new when it should not be used. (Are you a C# programmer, moving to C++?)
However, there are problems with the #include directives as well. As #Bo mentioned, since Person uses Dog, you should include that header in Person.h. But Person also uses vector so that header should be included there as well. So Person.h should start with...
#include <vector>
#include "Dog.h"
Then in Person.cpp you don't have to include those files.
As a general rule (you can learn about "forward declaration" later), any types referenced in a header should be #included in that header.