Passing pointer to array of objects into function - c++

When I run this code it crashes with out any errors. I have tried everything i know and done searches but i can figure this one out. It builds and runs fine and goes all the way to the cout in FleetCapacity and something about that line is making the code crash . When i commented out that line the code ran fine so im not sure as to why that line of code is causing my program to crash and burn.
#include <iostream>
#include <string>
using namespace std;
class Ship{
private:
string shipName;
string shipYear;
public:
Ship(string sN,string sY){shipName=sN; shipYear=sY;}
virtual void printInfo();
void setShipName(string);
virtual string getShipName();
void setShipYear(string);
string getShipYear();
};
class CruiseShip:public Ship{
private:
int maxPass;
int maxCrew;
public:
CruiseShip(string sN,string sY, int mP,int mC):Ship(sN,sY){setShipName(sN);maxPass=mP; maxCrew=mC; }
void printInfo();
void setMaxPass(int);
int getMaxPass();
void setMaxCrew(int);
int getMaxCrew();
};
class CargoShip:public Ship{
private:
int cargoCap;
public:
CargoShip(string sN,string sY,int cC):Ship(sN,sY){setShipName(sN);cargoCap=cC;}
void printInfo();
void setCargoCap(int);
int getCargoCap();
};
void Ship::setShipName(string sN){shipName=sN;}
string Ship::getShipName(){return shipName;}
void Ship::setShipYear(string sN){shipYear=sN;}
string Ship::getShipYear(){return shipYear;}
void Ship::printInfo(){
cout<<"The ships name is "<<shipName<<endl;
cout<<"The ships year is "<<shipYear<<endl;
}
void CruiseShip::printInfo(){
cout<<"The ships name is "<<getShipName()<<endl;
cout<<"The ships maximum passangers is "<<maxPass<<endl;
}
void CruiseShip::setMaxPass(int mP){maxPass=mP;}
int CruiseShip::getMaxPass(){return maxPass;}
void CruiseShip::setMaxCrew(int mC){maxCrew=mC;}
int CruiseShip::getMaxCrew(){return maxCrew;}
void CargoShip::printInfo(){
cout<<"The ships name is "<<getShipName()<<endl;
cout<<"The ships cargo capacity is "<<cargoCap<<endl;
}
int CargoShip::getCargoCap(){return cargoCap;}
void CargoShip::setCargoCap(int cC){cargoCap=cC;}
void fleetCapacity(Ship** s ,int e){
cout << "Name of ship: " << s[e]->getShipName() << endl;
}
int main()
{
const int NUMSHIPS = 3;
//int aSize = NUMSHIPS;
// array of ship pointers initialized with addresses of dynamically allocated class objects.
Ship *ships[NUMSHIPS] = {
new Ship("The Dinghy Berry", "1982"),
new CruiseShip("Disney Adventure Tours"," ",500,100),
new CargoShip("The Sea Trucker"," ", 50)
};
for (int i = 0; i < NUMSHIPS; i++ )
{
ships[i]->printInfo();
}
cout << "The entire fleet capacity is: ";
fleetCapacity(ships, NUMSHIPS);
cout << " tons." << endl;
return 0;
}

you are calling fleetCapacity(ships, NUMSHIPS); which is then accessing s[e] (ships[NUMSHIPS]) in the function. The valid indices are 0 through NUMSHIPS-1.

Related

Objects in Array are not being replaced by new Objects

This has been driving me insane for hours - I'm new to C++: I can't figure out why my programs thinks I want it do this.
I have a class House
class House{
private:
int number;
std::string family;
public:
House(int n, std::string f){
this->number = n;
this->family = f;
}
House(){
this->number = 0;
this->family = "unassigned";
}
void whoLivesHere(){
std::cout<<"The"<<family<<"lives here."<<std::endl;
}
};
I have another class Neighborhood
class Neighborhood{
private:
int size;
House houses[100];
public:
Neighborhood(){
this->size=0;
}
void addHouse(House h){
this->houses[this->size] = h;
this->size++;
}
void whoLivesHere(){
for(int i=0; i<this->size; i++){
this->houses[this->size].whoLivesHere();
}
}
};
And this is what is happening on my main.
int main(){
Neighborhood n1;
House h1(1,"Johnsons");
House h2(1,"Jones");
n1.addHouse(h1);
n1.addHouse(h2);
n1.whoLivesHere();
return 0;
}
And what I get on the Terminal is this.
The unassigned lives here
The unassigned lives here
The unassigned lives here
Why didn't the new objects replace the first two default objects?
Why show three objects? If size should be 1.
Thank you tonnes in advance!
You can make short work of this problem by using the tools the C++ Standard Library gives you, like this:
#include <string>
#include <vector>
#include <iostream>
int main() {
std::vector<House> neighborhood;
// emplace_back() forwards arguments to the constructor
neighborhood.emplace_back(1, "Johnson");
neighborhood.emplace_back(2, "Jones");
// No need to track size, std::vector does that for you: size(),
// but that's not even needed to iterate, you can just do this:
for (auto& house : neighborhood) {
house.whoLivesHere();
}
return 0;
}
Here I've cleaned up your House implementation:
class House {
private:
int number;
std::string family;
public:
// Tip: Use constructor lists
House(int n, const std::string& f) : number(n), family(f) { };
// Useful even for defaults
House() : number(0), family("unassigned") { };
// Flag methods that don't modify anything as const
void whoLivesHere() const {
std::cout << "The " << family << " lives here at number " << number << "." << std::endl;
}
};

Fuction-definition not allowed RetailItem

I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.

Array of pointers to an object in C++

I am trying to write a super basic program which creates an array of objects under class Receipt. The class includes an int price, string good (name), and a simple function that adds an item to the list. I am stuck because every time I compile it seg faults before it even gets to the add function, meaning something is wrong with my default constructor.
I am still really new to C++ and pointers are probably my biggest struggle. I have looked online and at my lecture notes trying to figure out what I am doing wrong. I feel like it's something small but I cannot figure it out.
Here is my program:
#include <iostream>
#include <string>
using namespace std;
class Receipt {
private:
int price;
string good;
Receipt* goods[500]; //partially filled array
public:
Receipt();
void add(string name, int cost);
string getName();
int getPrice();
void setName(string name_in);
void setPrice(int price_in);
void displayList();
};
Receipt::Receipt()
{
for (int i=0; i < 500; i++)
{
goods[i]->setName("Empty");
goods[i]->setPrice(-1);
}
}
void Receipt::add(string name, int cost)
{
int place=0;
for (int i=0; i <500; i++)
{
if (goods[i]->getName()=="Empty" && goods[i]->getPrice()==-1)
{
place = i;
break;
}
}
goods[place]->setName(name);
goods[place]->setPrice(cost);
}
int Receipt::getPrice()
{
return price;
}
string Receipt::getName()
{
return good;
}
void Receipt::setName(string name_in)
{
good = name_in;
}
void Receipt::setPrice(int price_in)
{
price = price_in;
}
void Receipt::displayList()
{
//just displaying first item in list for debugging purposes
cout << goods[0]->getName() << endl << goods[0]->getPrice();
}
int main()
{
Receipt mine; //seg faults here
mine.add("banana", 50);
mine.displayList();
return 0;
}
your design is wrong, you have array of Receipt inside Receipt so when you initialize the object, it create 500 where each of them create another 500 endlessly. I think you want to create something like this instead
#include <iostream>
#include <string>
using namespace std;
class Receipt {
private:
int price;
string good;
public:
void setName(string name_in);
void setPrice(int price_in);
string getName();
int getPrice();
};
class Receipts {
private:
Receipt* goods[500]; //partially filled array
public:
Receipts();
void add(string name, int cost);
void displayList();
};
Receipts::Receipts()
{
for (int i = 0; i < 500; i++)
{
goods[i] = new Receipt();
goods[i]->setName("Empty");
goods[i]->setPrice(-1);
}
}
void Receipts::add(string name, int cost)
{
int place = 0;
for (int i = 0; i <500; i++)
{
if (goods[i]->getName() == "Empty" && goods[i]->getPrice() == -1)
{
place = i;
break;
}
}
goods[place]->setName(name);
goods[place]->setPrice(cost);
}
int Receipt::getPrice()
{
return price;
}
string Receipt::getName()
{
return good;
}
void Receipt::setName(string name_in)
{
good = name_in;
}
void Receipt::setPrice(int price_in)
{
price = price_in;
}
void Receipts::displayList()
{
//just displaying first item in list for debugging purposes
cout << goods[0]->getName() << endl << goods[0]->getPrice();
}
int main()
{
Receipts mine; //seg faults here
mine.add("banana", 50);
mine.displayList();
return 0;
}

How can I assign class object into a class

I need to creat an object Pokemon in the main()
that assign it into the class PokemonWorld, and let the PokemonWolrd to decide which PokemonStation is this Pokemon need to go
I tired get the data separatly (get name and hp) and get together(get a Pokemon class)
but both fail
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class Pokemon {
public:
Pokemon() {};
Pokemon(char x[], int n) {
strncpy_s(name, x, 10);
hp = n;
};
private:
char name[10];
int hp;
};
class PokemonStation {
private:
Pokemon **list= new Pokemon*[1000];
public:
PokemonStation() {};
PokemonStation(int x) {
id = x;
};
int id;
void assigntoList(int i,Pokemon x)
{
if (i > 0)
i--;
list[i] = new Pokemon(x);
cout << "creat" << list[i];
};
};
class PokemonWorld {
private:
char name[10];
public:
PokemonStation s1;
PokemonStation s2;
PokemonWorld() {};
PokemonWorld(char x[], int y=1, int z=2) {
strncpy_s(name, x, 10);
PokemonStation s1(y);
PokemonStation s2(z);
};
const char* const getName() const{
return name;
};
void assigntoStation(int i,Pokemon x) {
if (i == 0 || i % 2 == 0)
s1.assigntoList(i, x);
else
s2.assigntoList(i, x);
};
};
void main() {
int number,hp,i;
char name[10];
cout << "What is the World Name ?" <<endl;
cin >> name;
PokemonWorld world(name);
cout << "Please input the number of Pokemon in the " << world.getName() <<" world:" << endl;
cin >> number;
Pokemon **mon = new Pokemon*[number];
cout << "Please input the characteristics of all Pokemon: Name HP" << endl;
for (i = 0;i < number;i++)
{
cin >> name >> hp;
mon[i] = new Pokemon(name, hp);
world.assigntoStation(i,*(mon[i]));
}
for (i = 0;i < number;i++)
cout << "world is " << world.getName() << endl;
system("pause");
};
In C++, you should use std::vectors for dynamic lists of things and std::strings for text. If you know Java, these are like ArrayList and String. (To use these, make sure you #include <vector> and <string>.)
For instance, your Pokemon class, rewritten with name as a string:
class Pokemon {
public:
Pokemon() {}
Pokemon(string name, int hp):name(name), hp(hp) { // construct the fields directly
}
private:
string name;
int hp;
};
And your PokemonStation class, rewritten using a vector for the list of Pokemon:
class PokemonStation {
private:
vector<Pokemon> list;
public:
PokemonStation() {}
PokemonStation(int x):id(x) {}
int id;
void assignToList(Pokemon x)
{
list.push_back(x); // add x to the list
}
};
If you want to print a Pokemon with cout <<, then you'll have to overload the << operator to define what gets printed. Add this into your class:
class Pokemon {
public:
...
friend ostream& operator<<(ostream& out, const Pokemon& p) {
out << p.name; // just print the name
return out;
}
...
};
Just make sure that you're couting a Pokemon, not a pointer-to-Pokemon (Pokemon*), and you won't get an address.

Dynamic object array increase

I'm building a domino game and trying to make a function that adds a Stone to a pile.
This is the Stone class:
class Stone
{
public:
Stone(){ left = 0; right = 0; };
Stone(int x, int y){ left = x; right = y; };
void turnStone();
bool comStones(const Stone&);
void printOpen();
void printClosed();
friend class Pile;
friend class Game;
private:
int left, right;
};
And this is the Pile class:
class Pile
{
public:
Pile(){};
Stone indexfun(int);
void printOpen();
void printClosed();
void fillPile();
void randPile();
void addStone(Stone&);
void remStone(Stone&);
friend class Player;
friend class Game;
private:
Stone* list;
int size=0;
};
Now the function I built for adding a stone to the pile is:
void Pile::addStone(Stone& newStone) {
Stone* newList = new Stone[size + 1];
int i;
for (i = 0; i < size; i++)
{
newList[i] = list[i];
}
newList[i] = newStone;
delete[] list;
list = newList;
size++;
}
When I try and build the newlist array it throws me out of the program. can't find the reason. Help anyone?
the previous functions and more classes in the project:
class Game
{
public:
Game(char*);
void run();
private:
Player human, computer;
Pile box, table;
int start, finish;
void playerMove(int);
void checkPile(int);
bool checkMove(int,int);
bool whosFirst();
bool checkGame();
void printTable();
};
class Player
{
public:
Player(){};
void addStone(Stone&);
void remStone(Stone&);
void printPile();
Stone* searchStone();
friend class Game;
private:
char* name;
Pile pie;
};
void Game::run() {
cout << "starting the game" << endl;
box.fillPile();
box.size = 28;
box.randPile();
for (int i = 0; i < 7; i++)
{
human.addStone(box.list[i]);
box.remStone(box.list[i]);
computer.addStone(box.list[i]);
box.remStone(box.list[i]);
}
}
void Player::addStone(Stone& added) {
pie.addStone(added);
}
int main()
{
char name[80];
cout << "enter your name" << endl;
cin >> name;
Game game(name);
game.run();
}
Maybe change the "list" variable name to "list1" or something like that. "list" is a STL container, just like vector.