Seg Fault with Class Constructors C++ - c++

I am new to classes and am having a lot of difficulty with the constructors. I have two constructors for a business class and whenever I attempt to create a business object or do anything with the business object I immediately Seg Fault. The business class interacts with an additional class called Customer. If anyone could offer any help I would greatly appreciate it.
Business.h
#ifndef BUSINESS_H
#define BUSINESS_H
#include <iostream>
#include <string>
#include "customer.h"
using namespace std;
class Business
{
public:
Business();
Business(string name, float cash);
void printData() const;
void addCustomer(Customer newCustomer);
void make_a_sale();
private:
string businessName;
float cashInReg;
string itemArray[10];
Customer custInBus[10];
short numOfItems;
short numOfCustom;
};
#endif
Business.cpp
#include "business.h"
#include <iostream>
#include <cstdlib>
using namespace std;
Business::Business(): businessName("Business"), cashInReg(0), numOfItems(0),
numOfCustom(0) {}
Business::Business(string name, float cash) : businessName(name),
cashInReg(cash), numOfCustom(0) {}
void Business::printData() const
{
cout << businessName <<endl;
for (int i=0; i<numOfCustom; i++)
{
cout << "\t Customer Name: " << custInBus[i].getName() <<endl;
}
for (int i=0; i<numOfItems; i++)
{
cout << "\t Item list: " <<itemArray[i] <<endl;
}
}
void Business::addCustomer(Customer newCustomer)
{
custInBus[numOfCustom-1] = newCustomer;
numOfCustom++;
}
void Business::make_a_sale()
{
int randomItem;
int currCustomer=0;
while (currCustomer < numOfCustom)
{
randomItem = rand() %tempItems;
custInBus[currCustomer].purchase(tempArray[randomItem]);
currCustomer ++;
}
}

void Business::addCustomer(Customer newCustomer)
{
custInBus[numOfCustom] = newCustomer;
//use numOfCustom instead of numOfCustom-1
numOfCustom++;
}

Related

multiple inheritance variables returning correctly

I'm working on a multiple inheritance exercise and I'm running into a strange error. My code is not returning the correct information to the console. It is just outputting zero, I have checked multiple times in my code and I can't seem to find anything obviously wrong. I'm fairly new to C++ so any help I would appreciate it, in addition to any other critique.
The console will output
Maverick
South station
50 - passengers, is ok
40 - speed
0 - it is supposed to take distance/mph and output 2.6 in this case, but is returning nothing.
MBTA.cpp
#include "MBTA.h"
//objects
transportation Dest;
MBTA::MBTA()
{
}
MBTA::MBTA(string strIn, string strInTransport, int iIn, int distIn, int eIn)
{
setTrain(strIn);
//Destination
Dest.setTransport(strInTransport);
//set passengers
setPass(iIn);
Dest.setMilesToDest(distIn);
engine.setMPH(eIn);
//outputs train information
printTrainDestinationHours();
//used printf as I was running into issue with using cout here
//cout << " I am going to ";
printf("I am going to %s\n", Dest.getTransport().c_str());
//uses engine stats function
cout << "I go " << engine.getMPH() << endl;
printf("It will take me %.2f hours to arrive", redline.getTotal());
}
void MBTA::setTravelDist(int iIn)
{
double destdistance = Dest.getDist();
double trainMPH = engine.getMPH();
//this divides miles by MPH, this might return a float
redline.setTotal(50, 10);
}
MBTA::~MBTA()
{
}
MBTA.H
#pragma once
#include "train.h"
class MBTA :
public train
{
public:
engine engine;
train redline;
MBTA();
//train, destination, passengers, traveldist, speed
MBTA(string, string, int, int, int);
void setTravelDist(int);
//double getTotal();
//uses engine stats function
//double total = 0;
~MBTA();
};
Train.cpp
#include "train.h"
#include <iostream>
#include <cstdio>
#include <cmath>
using std::string;
using std::cout;
using std::endl;
//object member for transport
transportation tTrain;
train::train()
{
}
void train::printTrainDestinationHours()
{
printf("\n\nTrain type: %s\n", getTrain().c_str());
//passengers
printf("I have %d passengers\n", getPass());
}
void train::setPass(int iIn)
{
passengers = iIn;
}
int train::getPass()
{
return passengers;
}
void train::setTrain(string strIn)
{
trainName = strIn;
}
string train::getTrain()
{
return trainName;
}
void train::setTotal(int aIn, int bIn)
{
//dist / mph
total = aIn / bIn;
}
double train::getTotal()
{
return total;
}
train::~train()
{
}
Train Header
#pragma once
#include <iostream>
#include <cstdio>
using std::string;
using std::cout;
using std::endl;
#include "engine.h"
#include "transportation.h"
class train : public transportation
{
public:
train();
void printTrainDestinationHours();
//set and get destination
//num of pass
void setPass(int);
int getPass();
//train
void setTrain(string);
string getTrain();
//distance
void setTotal(int, int);
double getTotal();
~train();
private:
engine engineStats;
int total = 0;
string trainName = "";
string destination = "";
int passengers = 0;
};
engine.cpp
#include "engine.h"
engine::engine()
{
}
void engine::setMPH(int iIn)
{
MPH = iIn;
}
int engine::getMPH()
{
return MPH;
}
engine::~engine()
{
}
engine header
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
'''
transportation cpp
'''
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
transportation header
#include "transportation.h"
transportation::transportation()
{
}
void transportation::setTransport(string strIn)
{
destination = strIn;
}
string transportation::getTransport()
{
return destination;
}
void transportation::setMilesToDest(int iIn)
{
MilesToDestination = iIn;
}
int transportation::getDist()
{
return MilesToDestination;
}
transportation::~transportation()
{
}
main file
#include <iostream>
using std::string;
using std::cout;
using std::endl;
using std::cin; //for ignore
#include "challenger.h"
#include "MBTA.h"
#include "plane.h"
int main()
{
//object composition of vehicle type
// vehicle type location, passengers, MPH , distance
challenger SRT8707("Boston", 2, 100, 200);
plane boeing("boeing", "houston", 50, 500, 300);
MBTA redline("Maverick", "South station", 50, 100, 40);
//pause and blank line
cout << endl << endl;
cin.ignore();
}

What is the proper way of passing a vector?

Im on year 10 and our teacher wants us to create an original project and using pointers
What I want to do is to create Members and be able to sort the members by there names and print them
When I run my code it says Invalid Access
Team.h
#ifndef TEAM_H
#define TEAM_H
#include "Staff.h"
#include <vector>
#include <iostream>
using std::vector;
class Team: public Staff
{
public:
Team();
~Team();
vector<Staff *> &getVector();
private:
vector<Staff *> myStaffs;
};
#endif // TEAM_H
Team.cpp
Team::Team()
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
vector<Staff*>& Team::getVector()
{
return myStaffs;
}
Command class will do the sorting of team and print all team members
Command.cpp
void Command::printStaffs(vector<Staff*>&myStaffs)
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
std::cout << "Staff ID number: "<< myStaffs[iStaff]->getStaId() << std::endl
<< "Staff Skills 1: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< "Staff Skills 2: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< "Staff Skills 3: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< std::endl;
}
}
Command.h
#ifndef CommandH
#define CommandH
#include "Team.h"
#include <vector>
#include <iostream>
using std::vector;
class Command: public Team
{
public:
Command(){}
~Command(){}
void sortVector(vector<Staff* >&vectorTemp);
void printStaffs(vector<Staff* >&);
private:
vector<Staff *> vectEmployee;
};
//--------------------------------------------------------------------------
#endif
main.cpp
#include <iostream>
#include <conio.h>
#include "Team.h"
#include "Command.h"
int main()
{
Team t;
Command c;
c.printStaffs(t.getVector());
getch();
return 0;
}
Staff.h
#ifndef STAFF_H
#define STAFF_H
#include <cstdlib>
#include <ctime>
#include <string>
using std::rand;
class Staff
{
public:
Staff();
~Staff();
static Staff* createStaff(int); // creates staffs
int** getStaSkill();
int getStaId(); // returns Staff ID
static int genRanNum(int); //Generate random number
private:
int *staSkill[3];
int staId;
//int staDeptAsigned;
};
#endif
Staff.cpp
#include "Staff.h"
Staff::Staff()
{
*staSkill = new int[3];
}
Staff *Staff::createStaff(int s)
{
Staff *staff = new Staff();
staff->staId = s;
*(staff->staSkill[0]) = genRanNum(10);
*(staff->staSkill[1]) = genRanNum(10);
*(staff->staSkill[2]) = genRanNum(10);
return staff;
}
int** Staff::getStaSkill()
{
return staSkill;
}
int Staff::getStaId()
{
return staId;
}
int Staff::genRanNum(int num)
{
return 1 +(std::rand()%num);
}
Staff::~Staff(){}
When you construct a Team, you have the following constructor:
Team::Team()
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
However, myStaffs is a member of Team and gets default constructed as empty, so nothing happens here since myStaffs.size() == 0.
Calling printStaffs on this Team::getVector() will correctly inform you that the vector is empty:
int main()
{
Command c;
Team t; // t.myStaffs will be empty
c.printStaffs(t.getVector()); // passes an empty vector to printStaffs
return 0;
}
You might want to pass a number to your Team constructor to create that many staffs:
Team::Team(int number_of_staff)
{
for(unsigned int iStaff = 0; iStaff < number_of_staff; iStaff++)
{
myStaffs.push_back(createStaff(iStaff));
}
}
int main()
{
Command c;
Team t(5); // t.myStaffs will contain 5 staff members
c.printStaffs(t.getVector()); // passes vector of 5 staff
return 0;
}

Classes in C++: Declaring an Instance

I have consulted many websites but have not successfully completed my code.
I am trying to write some code that spits out information about a car, once the user provides information. After compiling, the compiler says that "declaration does not declare anything." Here's the code:
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car()
{
}
void Car::accel()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}
void Car::setSpeed(int newSpeed)
{
speed = newSpeed;
}
int Car::getSpeed()
{
return speed;
}
void Car::setMake(string newMake)
{
make = newMake;
}
string Car::getMake()
{
return make;
}
void Car::setYearModel(int newYearModel)
{
yearModel = newYearModel;
}
int Car::getYearModel()
{
return yearModel;
}
int main()
{
Car auto; //instance of class Car
int autoYear; //year of auto
string autoMake; //make of auto
int autoSpeed; //speed of auto
cout << "Enter the year model of your car. ";
cin >> autoYear;
cout << "Enter the make of your car. ";
cin >> autoMake;
auto.setYear(autoYear); //stores input year
auto.setMake(autoMake); //stores input make
}
And the header, Car.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H
#define CAR_H
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car();
void accel();
void brake();
void setSpeed(int newSpeed);
int getSpeed();
void setMake(string newMake);
string getMake();
void setYearModel(int newYearModel);
int getYearModel();
};
#endif
I also have errors for missing semicolons every time my object auto appears ("expected ; before auto" and "expected primary-expression before auto"). What could be the problem?
auto is a keyword. You'll need to pick a different name.

C++ Insertion Sort a vector

I'm trying to do an insertion sort on a vector of baseball pitchers I created yesterday with help from a previous post. I want to sort the pitchers in ascending order by ERA1. I have gotten the insertion sort to work in the past for a set of integers. I think I have a syntax error in my code for the insertion sort. Up until trying to add the insertion sort this program was working well. I get an error - expected unqualified id before [ token. Thanks in advance for any help.
#ifndef Pitcher_H
#define Pitcher_H
#include <string>
#include <vector>
using namespace std;
class Pitcher
{
private:
string _name;
double _ERA1;
double _ERA2;
public:
Pitcher();
Pitcher(string, double, double);
vector<Pitcher> Pitchers;
string GetName();
double GetERA1();
double GetERA2();
void InsertionSort(vector<Pitcher>&);
~Pitcher();
};
#endif
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
Pitcher::Pitcher()
{
}
Pitcher::~Pitcher()
{
}
string Pitcher::GetName()
{
return _name;
}
Pitcher::Pitcher(string name, double ERA1, double ERA2)
{
_name = name;
_ERA1 = ERA1;
_ERA2 = ERA2;
}
double Pitcher::GetERA1()
{
return _ERA1;
}
double Pitcher::GetERA2()
{
return _ERA2;
}
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
void InsertionSort(vector<Pitcher> Pitchers&);
using namespace std;
int main()
{
vector<Pitcher> Pitchers;
cout << "Pitcher" << setw(19) << "Item ERA1" << setw(13) <<
"Item ERA2\n" << endl;
Pitcher h2("Bob Jones", 1.32, 3.49);
Pitchers.push_back(h2);
Pitcher h3("F Mason", 7.34, 2.07);
Pitchers.push_back(h3);
Pitcher h1("RA Dice", 0.98, 6.44);
Pitchers.push_back(h1);
for(unsigned i = 0; i < Pitchers.size(); ++i)
{
cout << setw(19);
cout << left << Pitchers[i].GetName() << "$" <<
setw(10) << Pitchers[i].GetERA1() <<
right << "$" << Pitchers[i].GetERA2() << "\n";
}
cout << endl;
//------------------------------------------------------
InsertionSort(Pitchers);
//Now print the numbers
cout<<"The numbers in the vector after the sort are:"<<endl;
for(int i = 0; i < Pitchers.size(); i++)
{
cout<<Pitchers[i].GetERA1()<<" ";
}
cout<<endl<<endl;
system("PAUSE");
return 0;
}
void InsertionSort(vector<Pitcher> &Pitchers)
{
int firstOutOfOrder = 0;
int location = 0;
int temp;
int totalComparisons = 0; //debug purposes
for(firstOutOfOrder = 1; firstOutOfOrder < Pitchers.size() ; firstOutOfOrder++)
{
if(Pitcher.GetERA1([firstOutOfOrder]) < Pitcher.GetERA1[firstOutOfOrder - 1])
{
temp = Pitcher[firstOutOfOrder];
location = firstOutOfOrder;
do
{
totalComparisons++;
Pitcher.GetERA1[location] = Pitcher.GetERA1[location - 1];
location--;
}while(location > 0 && Pitcher.GetERA1[location - 1] > temp);
Pitcher.GetERA1[location] = temp;
}
}
cout<<endl<<endl<<"Comparisons: "<<totalComparisons<<endl<<endl;
}
Here:
for(firstOutOfOrder = 1; firstOutOfOrder < Pitchers.size() ; firstOutOfOrder++)
{
if(Pitchers[firstOutOfOrder].GetERA1() < Pitchers[firstOutOfOrder-1].GetERA1())
{ //^^^your way was not right, should first access the object then
//access member function
temp = Pitcher[firstOutOfOrder];
//^^^should be Pitchers, similar errors below
location = firstOutOfOrder;
do
{
totalComparisons++;
Pitcher.GetERA1[location] = Pitcher.GetERA1[location - 1];
//^^^similar error as inside if condition
location--;
}while(location > 0 && Pitcher.GetERA1[location - 1] > temp);
//^^^similar error as inside if condition
Pitcher.GetERA1[location] = temp;
//^^similar error as in if condition and name error
}
}
Meanwhile, you put the InsertionSort declaration as a member of the Pitcher class
public:
.
.
void InsertionSort(vector<Pitcher>&);
and you also declare the same function inside main,
void InsertionSort(vector<Pitcher> Pitchers&);
//should be vector<Pitcher>& Pitchers
using namespace std;
int main()
the member function probably should be removed in your case. InsertionSort is not a responsibility of your Pitcher class.
Unless this is homework, you're better off using the build in sort from
<algorithm>

Templates C++ error : could not deduce template argument

I am trying ot add a function template that will print if it contains precision values or valves and the value. The rest of the program works except this function. I am not sure what I am doing wrong but the error I recieve is:
error C2784: 'void printInstrumentDetail(const I *const )' : could not deduce template argument for 'const I *const ' from 'std::vector<_Ty>'
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include "Instruments.h"
#include "Brass.h"
#include "Strings.h"
using namespace std;
//template<typename I> <---Problem
//void printInstrumentDetail(const I * const a)
//{
// for (size_t i = 0; i < 6; i ++)
// {
// cout << "The details for " << a[i]->getName()
// << ": " << a[i]->print();
// }
//}
int main()
{
double total = 0;
Strings violin("Violin", 553.90, 3);
Strings cello("Cello", 876.45, 3);
Strings viola("Viola", 200.50, 23);
Brass tuba("Tuba", 1400.10, 1.23);
Brass trumpet("Trumpet", 500.00, 4.32);
Brass sax("Sax", 674.78, .99);
vector <Instruments *> band(6);
band[0] = &violin;
band[1] = &tuba;
band[2] = &cello;
band[3] = &trumpet;
band[4] = &viola;
band[5] = &sax;
cout << fixed << setprecision(2);
cout << "The instruments in the band are:\n";
//Get name and cost of each
for (size_t i = 0; i < 6; i ++)
{
cout << band[i]->getName() << " $"
<< band[i]->getCost() << endl;
}
cout << "\nThen band is warming up..." << endl;
//Get descrition of how sound is made of each
for (size_t i = 0; i < 6; i ++)
{
cout << "This " << band[i]->getName()
<< " makes sounds by " ;
band[i]->playSound();
}
cout << "\nTotal cost of the band is: $" ;
//Get total cost of all instruments
for (size_t i = 0; i < 6; i ++)
{
total = band[i]->getCost() + total;
}
cout << total << endl;
//printInstrumentDetail(band); <--Problem
return 0;
}
Here's the base class:
#ifndef INSTRUMENTS_H
#define INSTRUMENTS_H
#include <string>
using namespace std;
class Instruments
{
public:
Instruments(string, double);
void setName(string);
virtual string getName();
void setCost(double);
virtual double getCost();
virtual void print();
virtual void playSound();
private:
string name;
double cost;
};
#endif
#include <iostream>
#include "Instruments.h"
using namespace std;
Instruments::Instruments(string n, double c)
{
name = n;
cost = c;
}
void Instruments::setName(string n)
{
name = n;
}
string Instruments::getName()
{
return name;
}
void Instruments::setCost(double c)
{
cost = c;
}
double Instruments::getCost()
{
return cost;
}
void Instruments::print()
{
}
void Instruments::playSound()
{
//empty
}
Derived class Bass:
#ifndef BRASS_H
#define BRASS_H
#include <string>
#include "Instruments.h"
using namespace std;
class Brass : public Instruments
{
public:
Brass(string, double, double);
void setPrecisionValue(double);
double getPrecisionValue();
void print() ;
void playSound();
private:
double precision;
string sound;
};
#endif
#include <iostream>
#include "Brass.h"
using namespace std;
Brass::Brass(string n, double c, double p)
:Instruments(n, c)
{
precision = p;
}
void Brass::setPrecisionValue(double p)
{
precision = p;
}
double Brass::getPrecisionValue()
{
return precision;
}
void Brass::print()
{
cout << getPrecisionValue() << endl;
}
void Brass::playSound()
{
cout << "blowing in a mouthpiece." << endl;
Instruments::playSound();
}
Derived class Strings:
#ifndef STRINGS_H
#define STRINGS_H
#include <string>
#include "Instruments.h"
using namespace std;
class Strings : public Instruments
{
public:
Strings(string, double, int);
void setValves(int);
int getValves();
void print();
void playSound();
private:
int valves;
};
#endif
#include <iostream>
#include "Strings.h"
using namespace std;
Strings::Strings(string n, double c, int v)
:Instruments(n, c)
{
valves = v;
}
void Strings::setValves(int v)
{
valves = v;
}
int Strings::getValves()
{
return valves;
}
void Strings::print()
{
cout<< getValves() << endl;
}
void Strings::playSound()
{
cout << "striking with a bow." << endl;
Instruments::playSound();
}
Well, the problem is that your template requires a pointer:
template<typename I>
void printInstrumentDetail(const I * const a);
but you're giving it a vector, not a pointer:
vector <Instruments *> band(6);
...
printInstrumentDetail(band);
You can hack your way around this by passing a pointer to the printInstrumentDetail function, like so:
printInstrumentDetail(&band[0]);
But really, you'd be much better off modifying printInstrumentDetail to take a container or a pair of iterators:
template <typename ContainerT>
void printInstrumentDetail(const ContainerT& a)
or
template <typename IteratorT>
void printInstrumentDetail(IteratorT first, IteratorT last)
with the appropriate modifications to the definition of the function.
Pass the pointer to vector
printInstrumentDetail(&band);
and inside printInstrumentDetail
(*a)[i]->getName();
Well, first off I don't believe you can pass a vector as a const * I const at
printInstrumentDetail(band);
Vector cannot be just cast to a pointer. One working solution would be something like:
template <typename T>
void printInstrumentDetail( const std::vector<T*>& band )
{
for ( size_t i = 0; i < band.size(); ++i )
cout << "The details for " << band[i]->getName()
<< ": " << band[i]->print();
}
And there are many others, including iterators, functors, STL algorithms, etc.
You are trying to pass an object to an interface that wants a pointer.
void printInstrumentDetail(const I * const a)
Convert this to a reference.
void printInstrumentDetail(I const I& a)
But to conform to the pattern that is common in C++. You should pass the beginning and end of the sequence as parameters. ie change your function to take itertors rather than a pointer.
Instead of passing the pointer:
printInstrumentDetail(const I * const a)
you can pass the reference:
printInstrumentDetail(const I& a)
Everything else stays unchanged.
First of all, there seems to be no reason for PrintInstrumentDetail to be a template at all -- it works with pointers to the base class, and unless you're likely to have other types with getName() and print() members to which it might be applied, it can/could/should just work with pointers to the base class.
Second, I'd think hard about changing how you do the job. Instead of a member function in each Instrument, and PrintInstrumentDetail to loop over all the instruments, I'd think hard about defining operator<< for Instrument, and using a standard algorithm to print out the details.
Looking at it, I think a few other things should change as well. First of all, unless you're dealing with really unusual instruments, the number of valves on a brass instrument is fixed forever -- so it should NOT have a SetValve() member. Rather, the number of valves should be set during construction, but not be open to change afterwards.
String instruments don't have valves at all (at least most normal ones don't), so they shouldn't have SetValves(), GetValves(), or anything else related to valves.
Likewise, unless you're doing something pretty unusual, the cost of an instrument can never change -- you paid what you paid, so the cost should be set during construction, and not open to later alteration.
Edit: one other thing: instead of hard-coding 6 everywhere, use band.size() to loop over all the instruments in the band.