C++ Setter doesn't change the object's variable value - c++

I'm trying to run a code that its's meant to change the value of object variables after it creates the object, and it isn't changing, then the variable is returning values like -815470397 and not changing. And when I use breakpoints it's like it jumps the inside part of the setter.
Pessoa.h
#pragma once
using namespace std;
class Pessoa
{
protected:
int dia;
int mes;
int ano;
int idade;
public:
Pessoa();
Pessoa(int, int, int, int);
int GetDia();
void SetDia(int);
int GetMes();
void SetMes(int);
int GetAno();
void SetAno(int);
int GetIdade();
void SetIdade(int);
};
Pessoa.cpp
#include "Pessoa.h"
Pessoa::Pessoa() {
}
Pessoa::Pessoa(int dia, int mes, int ano, int idade) {
this->dia = dia;
this->mes = mes;
this->ano = ano;
this->idade = idade;
}
int Pessoa::GetDia() {
return this->dia;
}
int Pessoa::GetMes() {
return this->mes;
}
int Pessoa::GetAno() {
return this->ano;
}
int Pessoa::GetIdade() {
return this->idade;
}
void Pessoa::SetDia(int dia) {
this->dia == dia;
}
void Pessoa::SetMes(int mes) {
this->mes == mes;
}
void Pessoa::SetAno(int ano) {
this->ano == ano;
}
void Pessoa::SetIdade(int idade) {
this->idade == idade;
}
Exame_especial.cpp
#include <iostream>
#include <string>
#include "Pessoa.h"
using namespace std;
string ImprimeIdade(Pessoa*);
int Calc_Idade(Pessoa*, int, int, int);
int main()
{
Pessoa* Einstein = new Pessoa();
Pessoa* Newton = new Pessoa();
Einstein->SetDia(14);
Einstein->SetMes(3);
Einstein->SetAno(1879);
Newton->SetDia(4);
Newton->SetMes(1);
Newton->SetAno(1643);
cout << ImprimeIdade(Newton) << endl;
cout << ImprimeIdade(Einstein) << endl;
}
string ImprimeIdade(Pessoa* nome) {
nome->SetIdade(Calc_Idade(nome, 29, 6, 2021));
return "A idade de Einstein seria " + to_string(nome->GetIdade()) + "\n";
}
int Calc_Idade(Pessoa* nome, int dia, int mes, int ano) {
int idade = ano - nome->GetAno();
if (nome->GetMes() > mes) {
idade = idade - 1;
}
else {
if (nome->GetMes() == mes) {
if (nome->GetDia() > dia) {
idade = idade - 1;
}
}
}
return idade;
}

You get these strange values due to the fact that your data members are of built-in type and they remain uninitialized when you use them. They remain uninitialized because your setters aren't setting anything. What they actually do is a comparison (the ==).
Pay attention to the difference in these two:
void Pessoa::SetDia(int dia) {
this->dia == dia; // Equal? Returns bool value which is lost
}
Vs
void Pessoa::SetDia(int new_dia) {
this->dia = new_dia; // Assigns a new value
}
This goes for all setters in your code.
Also, note that inside the body of a member function, you can refer to the data members directly, without the need to dereference them via this:
void Pessoa::SetDia(int new_dia) {
// Assigns new value to the dia data member of this
dia = new_dia;
}

Related

Changing a value of an element in an object that is stored in a vector in another object through an external function in C++

So made a class called ‘Item’, and the object of that class will have a 100% condition at the start, the Player stores items (with name “apple” in this case) whenever I tell him to. In the degradeT function I want to pass the whole vector containing the items that the player has picked up by far and then change the condition of each Item in that vector by -1 through the chCond function.
first error:
initial value of reference to non-const must be an lvalue
second error:
'void degradeT(std::vector<Item,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector<Item,std::allocator<_Ty>>' to 'std::vector<Item,std::allocator<_Ty>> &'
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::string; using std::vector; using std::to_string;
class Item {
private:
string name; // Item name
float condition; // Item condition
bool consumable; // Is the item consumable
public:
Item() {}
Item(string a, float b, bool c) { name = a; condition = b; consumable = c; }
Item(string a, bool c) { name = a; condition = 100.f; consumable = c; }
string getName() {
return name;
}
float getCond() {
return condition;
}
bool isCons() {
return consumable;
}
void chCond(float a) { // Change Item condition
condition += a;
}
};
//-----------------------
class Player {
private:
vector<Item> plItems; // Item container
public:
Player() {}
void pickUpItem(Item a) { // Adding Items to inventory
plItems.push_back(a);
cout << a.getName() << " added to inventory!\n";
}
void checkItemConds() { // Checking condition of all items
for (unsigned int a = 0, siz = plItems.size(); a < siz; a++) {
cout << plItems[a].getName() << "'s condition is: " << plItems[a].getCond() << "%\n";
}
}
Item returnItem(unsigned int a) { // Return a specific Item
return plItems[a];
}
int getCurInvOcc() { // Get cuurent inventory occupation
return plItems.size();
}
vector<Item> getPlItems() { // Return the vector (Item container)
return plItems;
}
};
//-------------------------
void degradeT(vector<Item>& Itemss); // Degrade item after some time
//-------------------------
int main()
{
Player me; // me
string inp; // input
int num = 1; // apple 1, apple 2, apple 3...
while (inp != "exit") {
cin >> inp;
if (inp == "addApple") {
Item apple(("apple " + to_string(num)), true);
me.pickUpItem(apple);
num++;
}
if (inp == "checkItemConds") {
me.checkItemConds();
}
if (inp == "timeTick") {
// This doesn't have anything to do with time I just want to test the function manually
degradeT(me.getPlItems());
}
}
system("PAUSE");
return 0;
}
void degradeT(vector<Item> &Itemss) {
for (unsigned int a = 0, siz = Itemss.size(); a < siz; a++) {
Itemss[a].chCond(-1);
cout << Itemss[a].getName() << endl;
}
}
I'm not sure what your question is, but your error is related to the function void degradeT(vector<Item> & Itemss).
This functions expects a reference but you are passing an r-value. You can either return a reference with getPlItems() or pass an l-value to degradeT.

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;
}

C++ - Segmentation fault when returning a string

I have this class
#include "Room.h"
#include "Book.h"
#include <cstdlib>
#include <iostream>
static int book_counter = 100;
//Constructors
Book::Book() {
for(int i = 0; i < 13; i++) {
this->customer_name += 97 + rand() % 26;
}
this->arrival = rand() % 30;
this->duration = 1 + (rand() % 10);
this->ppl = 1 + rand() % 5;
this->room = nullptr;
this->book_code = book_counter++;
}
Book::Book(std::string nm, int arr, int dur, int ppl) {
this->customer_name = nm;
this->arrival = arr;
this->duration = dur;
this->ppl = ppl;
this->room = nullptr;
this->book_code = book_counter++;
}
//Methods
int Book::getArr() {
return arrival;
}
int Book::getDur() {
return duration;
}
int Book::getPpl() {
return ppl;
}
void Book::anathesi(Room* x) {
this->room = x;
}
int Book::getBookCode() {
return book_code;
}
Room* Book::getRoom() {
return room;
}
std::string Book::getCustomerName() {
return customer_name;
}
which includes a string getter method getCustomerName().
When I call this method on main, via an instance created via the first constructor, everything works fine. On the other hand, if the instance is created via the second constructor, the method will cause a segmentation fault.
It seems like customer_name has an infinite length, thus causing a segmentation fault when I try to return it.
The method is called in main with this line of code:
cout << hotel.getBooks(i)->getBookCode() << " " << hotel.getBooks(i)->getCustomerName()
<< " " << hotel.getBooks(i)->getRoom()->getRoomCode() << "\n";
I am new into C++, so please elaborate my fault as much as needed.
The header file for class Book:
#ifndef PROJECT_BOOK_H
#define PROJECT_BOOK_H
#include <string>
class Room;
class Book {
protected:
std::string customer_name;
int book_code;
int arrival;
int duration;
int ppl;
Room* room;
public:
Book();
Book(std::string nm, int arr, int dur, int ppl);
void anathesi(Room* x);
int getArr();
int getDur();
int getPpl();
int getBookCode();
std::string getCustomerName();
Room* getRoom();
};
#endif //PROJECT_BOOK_H
In Hotel.h:
private: std::vector<Book*> books;
public: Book* getBooks(int i);
In Hotel.cpp:
Book* Hotel::getBooks(int i) {
return books[i];
}
Found the problem and fixed it.
I was creating instances with this piece of code:
Book obj(onoma, afiksh - 1, meres, arithmos);
which caused the segmentation I said.
I changed this to:
Book *obj = new Book(onoma, afiksh - 1, meres, arithmos);
and fixed the problem. Thanks for your time and help.
Unfortunately, I don't really know why this works, but it does, everything functions properly. Therefore I guess I'll have to look at new documentation.

C++ object member integer has ridiculous value (WTF)

This is for a poker game and I have class PokerTable defined in PokerTable.h
#include <iostream>
using namespace std;
class PokerTable
{
private:
int numPlayers;
int numPlaying;
int dealerPos;
int bigBlind;
int potSize;
int betSize;
bool flop;
bool turn;
bool river;
public:
//constructors
PokerTable();
PokerTable(int,int,int,int,int,bool,bool,bool);
//getters
int getNumPlayers(){return numPlayers;};
int getDealerPos(){return dealerPos;};
int getBigBlind(){return bigBlind;};
int getNumPlaying(){return numPlaying;};
int getPotSize(){return potSize;};
int getBetSize(){return betSize;};
bool getFlop(){return flop;};
bool getTurn(){return turn;};
bool getRiver(){return river;};
//void buttonShow(int);
//setters
void setBetSize(int inBetSize){betSize = inBetSize;};
void setBigBlind(int inBigBlind){bigBlind = inBigBlind;};
void setNumPlaying(int inNumPlaying){numPlaying = inNumPlaying;};
void setPotSize(int inPotSize){potSize = inPotSize;};
void setFlop(bool inFlop){flop = inFlop;};
void setTurn(bool inTurn){turn = inTurn;};
void setRiver(bool inRiver){river = inRiver;};
void setNumPlayers(int inPlayers){numPlayers = inPlayers;};
void setDealerPos(int inDealerPos){dealerPos = inDealerPos;};
};
PokerTable::PokerTable()
{
numPlayers = 9;
numPlaying = 9;
dealerPos = 1;
bigBlind = 20;
flop = false;
turn = false;
river = false;
}
PokerTable::PokerTable(int playerNum, int playingCount, int posDealer, int blindBig,int inPotSize, bool inFlop,bool inTurn,bool inRiver)
{
numPlayers = playerNum;
numPlaying = playingCount;
dealerPos = posDealer;
potSize = inPotSize;
bigBlind = blindBig;
flop = inFlop;
turn = inTurn;
river = inRiver;
}
In my watch list pokerTable.numPlayers has a random value up to 4 million before I even execute this next line of code.
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
and afterwards here is pokerTable in my watch list:
- aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...} PokerTable
betSize 30 int
bigBlind 1 int
dealerPos 9 int
flop false bool
numPlayers 2990892 int
numPlaying 9 int
potSize 20 int
river false bool
turn false bool
Can anyone tell me why all the values are not what I declared them to be??!?!!
And how I can fix this?
This is Form1.h
#pragma once
#include "PokerTable.h"
#include "Card.h"
#include <time.h>
#include "PokerPlayer.h"
#include <fstream>
#include <string>
#include <sstream>
//global variables
//TODO make players start from 0
int firstPlayer;
int deck[52];
int nextCard=0;
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
PokerPlayer players[9]; //however many players
ofstream gameLog;
/*
void setTable()
{
aPokerTable.setNumPlayers(9);
aPokerTable.setNumPlaying(9);
aPokerTable.setDealerPos(1);
aPokerTable.setBigBlind(20);
aPokerTable.setPotSize(30);
aPokerTable.setBetSize(20);
aPokerTable.setFlop(false);
aPokerTable.setTurn(false);
aPokerTable.setRiver(false);
}
*/
string convertInt(int number) //convert to string
{
stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
void createPlayers()
{
// aPokerTable.setNumPlayers(9);
for(int x=0;x<=(aPokerTable.getNumPlayers()-1);x++)
{
players[x] = *(new PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1));//1000 chips, position i+1, not folded
}
}
void playRound()
{
int action;
for(int playerTurn = firstPlayer; playerTurn <= aPokerTable.getNumPlayers()+firstPlayer; playerTurn++)
{
if(players[playerTurn].getFold() == false)
{
if(aPokerTable.getNumPlaying() == 1)
{
players[playerTurn].setChipStack(players[playerTurn].getChipStack() + aPokerTable.getPotSize()); //player wins pot
}
else //there is more than one person playing
{
action = players[playerTurn].action(); //0 is check/fold, value is call/bet/raise,
if(action > aPokerTable.getBetSize())
{
aPokerTable.setBetSize(action);
aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
playerTurn = playerTurn - aPokerTable.getNumPlayers();
}
else if (action == aPokerTable.getBetSize()) //call
{
aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
}
else //action < aPokerTable.betSize
{
players[playerTurn].setFold(true);
aPokerTable.setNumPlaying(aPokerTable.getNumPlaying()-1); //removes player from playing tally
}
}
}
}
}
void randomDeck()
{
int random_integer;
int tempCard;
//srand((unsigned)time(0));
for(int j=0;j<=51;j++)
{
deck[j] = j;
}
for(int i=51; i>=1; i--)
{
random_integer = rand()%(i); //a random number between 0 and i
tempCard = deck[i];
deck[i] = deck[random_integer]; //put the random card from unshuffled deck into slot i of the deck
deck[random_integer] = tempCard; //put whatever was at slot i into the random slot
}
}
void dealCards()
{
for(int j=1;j<=aPokerTable.getNumPlayers();j++)
{
players[j].setCard1(deck[nextCard]);
nextCard++;
players[j].setCard2(deck[nextCard]);
nextCard++;
}
}
void playPreFlop()
{
aPokerTable.setBetSize(aPokerTable.getBigBlind());
aPokerTable.setFlop(false); //it is before the flop
aPokerTable.setTurn(false);
aPokerTable.setRiver(false);
randomDeck(); //shuffle cards
dealCards();
firstPlayer = (aPokerTable.getDealerPos() + 3)%(aPokerTable.getNumPlayers()); // first player is left of blinds between 0 and numplayers
playRound();
}
void playFlop()
{
aPokerTable.setFlop(true);
firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
}
void playTurn()
{
aPokerTable.setTurn(true);
firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
}
void playRiver()
{
aPokerTable.setRiver(true);
firstPlayer = (aPokerTable.getDealerPos())%(aPokerTable.getNumPlayers()); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
if(aPokerTable.getNumPlaying() >=2)
{
//showDown();
}
}
/*
void showDown()
{
}
*/
This is pokerPlayer.h
using namespace std;
class PokerPlayer
{
private:
int chipStack,position;
bool fold;
int card1,card2;
public:
//constructors
PokerPlayer();
PokerPlayer(int,int,bool,int,int);
//getters
int getChipStack() {return chipStack;}
int getPosition() {return position;}
int getCard1(){return card1;}
int getCard2(){return card2;}
bool getFold(){return fold;}
//setters
void setChipStack(int inChips){chipStack = inChips;}
void setPosition(int inPos){position = inPos;}
void setCard1(int inCard1){card1 = inCard1;}
void setCard2(int inCard2){card2 = inCard2;}
void setFold(bool inFold){fold = inFold;}
int action();
};
PokerPlayer::PokerPlayer()
{
chipStack = 1000;
position = 0;
fold=false;
card1 = 0;
card2 = 1;
}
PokerPlayer::PokerPlayer(int inChipStack,int inPos, bool inFold, int inCard1, int inCard2)
{
chipStack = inChipStack;
position = inPos;
fold = inFold;
card1 = inCard1;
card2 = inCard2;
}
int PokerPlayer::action()
{
return 0;
}
aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...}
Note that dealerPos got assigned the value 9, that's wrong as well. If you look closely, you'll see that everything is shifted by 4 bytes.
Two possible reasons. The debugger could have picked the wrong address for aPokerTable, the actual address minus 4. That's unlikely. Or there's a mismatch between the definition of the PokerTable class as seen by pokertable.cpp and the other .cpp files that #include the pokertable.h include file. Where pokertable.cpp saw an extra member before the numPlayers member. Maybe you edited the header and deleted that member but ended up not recompiling pokertable.cpp for some mysterious reason. Build + Rebuild to fix. Do panic a bit if this actually works.
It's because in C++ before the constructor is called, variable uses the value that it already contains in its memory location that is a "random" value
I cannot reconstruct it because i dont have the full code. However, a random value near 4 million sounds like a pointer. When you store or retrieve a member variable maybe you did not de-reference the pointer. Please post the rest of the code so we can check if that's the case.
players[x] = *(new PokerPlayer(...));
That is a memory leak. What you probably want is:
players[x] = PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1);