Class | Modules: bus issue - c++

I am a C ++ beginner and I am working with classes and modules. When I try to run the app, the app gives me the following error: zsh: bus error /Users/****/Documents/jacoProject/App. On the internet I searched a lot, but I found things that I didn't understand and that I couldn't apply to my code.
Should I implement a destructor? If so how can I implement it with my class? Thanks in advance
func.cxx
module;
#include <string>
export module airline_ticket;
export class AirlineTicket
{
public:
AirlineTicket();
double calculatePriceInDollars();
std::string getPassengerName();
void setPassengerName(std::string name);
int getNumberOfMiles();
void setNumberOfMiles(int miles);
bool hasEliteSuperRewardsStatus();
void setHasEliteSuperRewardsStatus(bool status);
private:
std::string q_passengerName;
int q_numberOfMiles;
bool q_hasEliteSuperRewardsStatus;
};
func_impl.cxx
module;
#include <string>
module airline_ticket;
AirlineTicket::AirlineTicket()
{
q_passengerName = "..not";
q_numberOfMiles = 0;
q_hasEliteSuperRewardsStatus = false;
}
double AirlineTicket::calculatePriceInDollars()
{
if (hasEliteSuperRewardsStatus())
{
return 0;
}
else
{
return getNumberOfMiles() * 0.1;
}
}
std::string AirlineTicket::getPassengerName()
{
return q_passengerName;
}
void AirlineTicket::setPassengerName(std::string name)
{
q_passengerName = name;
}
int AirlineTicket::getNumberOfMiles()
{
return q_numberOfMiles;
}
void AirlineTicket::setNumberOfMiles(int miles)
{
q_numberOfMiles = miles;
}
bool AirlineTicket::hasEliteSuperRewardsStatus()
{
return q_hasEliteSuperRewardsStatus;
}
void AirlineTicket::setHasEliteSuperRewardsStatus(bool status)
{
q_hasEliteSuperRewardsStatus = status;
}
main.cpp
#include <iostream>
import airline_ticket;
int main()
{
AirlineTicket myTicket;
myTicket.setPassengerName("Will SMith");
myTicket.setNumberOfMiles(450);
double ticketCost {myTicket.calculatePriceInDollars()};
std::cout << ticketCost << std::endl;
return 0;
}

Related

'Read access violation' exception in an SFML/C++ project:

I'm recently learning to make a 2d game in SFML using a tutorial series on youtube by Suraj Sharma(Video 57):
https://www.youtube.com/watch?v=kwd_AVCkvXE&list=PL6xSOsbVA1ebkU66okpi-KViAO8_9DJKg&index=57
His Source Code:
https://github.com/Headturna/SFML_RPG
Right now he's teaching me to symplify the game's menu system by making a mini class 'StateData' in the parent class 'State' so any inherited class can access 'State' parameters via 'StateData'(Ex:MainMenu(StData* Stdata){}).
After debugging the game seems to runs fine.But everytime i click on something on the menu(start,settings,etc...) a 'Read access violation:Stdata was nullptr' occurs in the 'State' class constructor.
Here's the code:
State.h:
#pragma once
#ifndef STATE_H
#define STATE_H
#include "Player.h"
#include "GrphSettings.h"
class Player;
class GrphSettings;
class State;
class StData {
public:
StData(){}
//Vars
float GridSize;
sf::RenderWindow* Window;
GrphSettings* GSettings;
std::map<std::string, int>* SupportedKeys;
std::stack<State*>* states;
};
class State
{
private:
protected:
StData* Stdata;
std::stack<State*>* states;
sf::RenderWindow* window;
std::map<std::string, int>* SupportedKeys ;
std::map<std::string, int> Keybinds;
bool quit;
bool pause;
float keyTime;
float keyTimeMax;
float GridSize;
sf::Vector2i MousePosScr;
sf::Vector2i MousePosWind;
sf::Vector2f MousePosView;
//Resources
std::map<std::string,sf::Texture> texture;
//Funcs
virtual void InitKeybinds() = 0;
public:
State(StData* Stdata);
virtual~State();
//Access
const bool getKeytime();
const bool& getquit()const;
//Funcs
void Endstate();
void PauseSt();
void UnPauseSt();
virtual void UpdateInput(const float& dt) = 0;
virtual void UpdateMousePos();
virtual void UpdateKeyTime(const float& dt);
virtual void Update(const float& dt) = 0;
virtual void Render(sf::RenderTarget* target = nullptr) = 0;
};
#endif // !1
State.cpp:
#include "pch.h"
#include "State.h"
State::State(StData* Stdata)
{
this->Stdata = Stdata;
this->window = Stdata->Window;
this->SupportedKeys = Stdata->SupportedKeys;
this->states = Stdata->states;
this->quit = false;
this->pause = false;
this->keyTime = 0.f;
this->keyTimeMax = 10.f;
this->GridSize = Stdata->GridSize;
}
State::~State()
{
}
//Access
const bool State::getKeytime()
{
if (this->keyTime >= this->keyTimeMax) {
this->keyTime = 0.f;
return true;
}
return false;
}
const bool& State::getquit() const
{
// TODO: insert return statement here
return this->quit;
}
//Funcs
void State::Endstate()
{
this->quit = true;
}
void State::PauseSt()
{
this->pause = true;
}
void State::UnPauseSt()
{
this->pause = false;
}
void State::UpdateMousePos()
{
this->MousePosScr = sf::Mouse::getPosition();
this->MousePosWind = sf::Mouse::getPosition(*this->window);
this->MousePosView = this->window->mapPixelToCoords(sf::Mouse::getPosition(*this->window));
}
void State::UpdateKeyTime(const float& dt)
{
if (this->keyTime < this->keyTimeMax)
this->keyTime += 100.f * dt;
}
Every button one the menu(start,exit...)is an inherited state from 'State' class.This is,for example,the 'Edit' state.
Edit.h:
#pragma once
#ifndef EDIT_H
#define EDIT_H
#include "State.h"
#include "Gui.h"
#include "PauseMenu.h"
#include "TileMap.h"
class State;
class Gui;
class PauseMenu;
class TileMap;
class Edit:public State
{
private:
//Vars
sf::Font Fnt;
PauseMenu* PMenu;
std::map<std::string, gui::Button*> buttons;
TileMap Map;
//Functions
void InitVars();
void InitBackGrnd();
void InitFonts();
void InitKeybinds();
void InitPauseMenu();
void InitBtn();
public:
Edit(StData* Stdata);
virtual~Edit();
//Functions
void UpdateInput(const float& dt);
void Update(const float& dt);
void UpdatePButtons();
void UpdateBtn();
void Endstate();
void RenderBtn(sf::RenderTarget& target);
void Render(sf::RenderTarget* target = nullptr);
};
#endif // ! EDIT_H
Edit.cpp:
#include "pch.h"
#include "Edit.h"
void Edit::InitVars()
{
}
void Edit::InitBackGrnd()
{
}
void Edit::InitFonts()
{
if (!this->Fnt.loadFromFile("Fonts/SPACEMAN.ttf")) {
throw("Error::Edit::Couldn't load font");
}
}
void Edit::InitKeybinds()
{
std::ifstream ifs("Config/EditKeys.ini");
if (ifs.is_open()) {
std::string key = "";
std::string key2 = "";
int keyval = 0;
while (ifs >> key >> key2)
{
this->Keybinds[key] = this->SupportedKeys->at(key2);
}
}
ifs.close();
this->Keybinds["Close"] = this->SupportedKeys->at("ESC");
this->Keybinds["Left"] = this->SupportedKeys->at("A");
this->Keybinds["Right"] = this->SupportedKeys->at("D");
this->Keybinds["Up"] = this->SupportedKeys->at("W");
this->Keybinds["Down"] = this->SupportedKeys->at("S");
}
void Edit::InitPauseMenu()
{
this->PMenu = new PauseMenu(*this->window, this->Fnt);
this->PMenu->addButtons("Quit", 800.f, "Quit");
}
void Edit::InitBtn()
{
}
Edit::Edit(StData* Stdata)
:State(Stdata)
{
this->InitVars();
this->InitBackGrnd();
this->InitFonts();
this->InitKeybinds();
this->InitPauseMenu();
this->InitBtn();
}
Edit::~Edit()
{
auto it = this->buttons.begin();
for (it = this->buttons.begin(); it != this->buttons.end(); ++it) {
delete it->second;
}
delete this->PMenu;
}
//Funcs
void Edit::UpdateInput(const float& dt)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key(this->Keybinds.at("Close")))
&& this->getKeytime()) {
if (!this->pause)
this->PauseSt();
else this->UnPauseSt();
}
}
void Edit::Update(const float& dt)
{
this->UpdateMousePos();
this->UpdateKeyTime(dt);
this->UpdateInput(dt);
if (!this->pause) {//Unpaused
this->UpdateBtn();
}
else {//Paused
this->PMenu->Update(this->MousePosView);
this->UpdatePButtons();
}
this->UpdateBtn();
std::cout << this->MousePosView.x << " " << this->MousePosView.y << "\r";
}
void Edit::UpdatePButtons()
{
if (this->PMenu->isPressed("Quit"))
this->Endstate();
}
void Edit::UpdateBtn()
{ //Update buttons and handle their functions
for (auto& it : this->buttons) {
it.second->Update(MousePosView);
}
}
void Edit::Endstate()
{
std::cout << "Ending State" << "\n";
}
void Edit::RenderBtn(sf::RenderTarget& target)
{
for (auto& it : this->buttons) {
it.second->Render(target);
}
}
void Edit::Render(sf::RenderTarget* target)
{
if (!target)
target = this->window;
this->RenderBtn(*target);
this->Map.Render(*target);
if (this->pause) {//Pause Menu
this->PMenu->Render(*target);
}
sf::Text MText;
MText.setPosition(this->MousePosView);
MText.setFont(this->Fnt);
MText.setCharacterSize(12);
std::stringstream ss;
ss << this->MousePosView.x << ' ' << this->MousePosView.y;
MText.setString(ss.str());
target->draw(MText);
}
Can anyone help me ?

Clang LibTooling - How to use DependencyCollector

I'm trying to use the DependencyCollector class of Clang in my Tool to list all the dependencies in a file, lets say test.cpp
Here is my program:
#include "stdafx.h"
#include <iostream>
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/Utils.h"
using namespace std;
using namespace clang::tooling;
using namespace clang;
using namespace llvm;
static cl::OptionCategory MyToolCategory("my-tool options");
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp MoreHelp("\nMore help text...");
class myDependencyCollector : public DependencyCollector {
private:
public:
bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsMissing) {
if (Filename == "stdafx.h" || IsSystem) {
return false;
} else {
return true;
}
}
bool needSystemDependencies() {
return false;
}
};
class DependencyAction : public PreprocessOnlyAction {
private:
myDependencyCollector *col;
public:
virtual bool usesPreprocessOnly() const {
return true;
}
bool BeginSourceFileAction(CompilerInstance &ci) {
Preprocessor &pp = ci.getPreprocessor();
col = new myDependencyCollector();
col->attachToPreprocessor(pp);
return true;
}
void ExecuteAction() {
}
virtual void EndSourceFileAction() {
llvm::ArrayRef<string> arr = col->getDependencies();
int size = arr.size();
for (int i = 0; i < size; i = i+1) {
cout << arr[i] << endl;
}
}
};
int main(int argc, const char **argv)
{
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
int result = Tool.run(newFrontendActionFactory<DependencyAction>().get());
return result;
}
Now, if I run the program on, for example the file test.cpp:
#include <iostream>
#include "test.h"
void do_math(int *x) {
*x += 5;
}
int main(void) {
int result = -1, val = 4;
do_math(&val);
return result;
}
The program doesn't find any includes.
It would be great if anybody could help me because I have not been able to find an answer after hours of searching on the internet.
The problem is that you overwrite the ExecuteAction() method from class PreprocessOnlyAction with an empty body.
If you delete the line:
void ExecuteAction() {}
everything works as expected.

Builder design pattern does not work for me

I have a problem with a c++ code I just written. The code is a sample of the Builder design pattern. I created an abstract builder class, and two classes inherited from this class: MonsterBuilder and RuffianBuilder. I created a Builder class, this class receives a Monster or a RuffianBuilder, and constructs a new instance of these classes. The problem comes here: if the MonsterBuilder class is used to build a new instance the program terminates with an error (a.exe has stopped working). If the Builder receives a RuffianBuilder, it constructs a new instance without an error. Here is the sample code:
#include <iostream>
class Character
{
private:
// Attributes
int dex;
int str;
int end;
// skills
int lockpick;
int guns;
int sneak;
/***************************************** Setters ********************************************************/
// Attribute setters
public:
void setStrength(const int &s)
{
this->str = s;
}
void setDexterity(const int &d)
{
this->dex = d;
}
void setEndurance(const int &e)
{
this->str = e;
}
// Skill setters
void setLockpick(const int &s)
{
this->lockpick = s;
}
void setSneak(const int &s)
{
this->sneak = s;
}
void setGuns(const int &s)
{
this->guns = s;
}
int getGuns()
{
return this->guns;
}
int getStrength()
{
return this->str;
}
};
/* Abstract builder */
class CharacterBuilder
{
protected:
Character * int_character;
public:
Character * getCharacter()
{
return int_character;
}
void buildCharacter()
{
int_character = new Character;
}
virtual void buildSkills() = 0;
virtual void buildAttributes() = 0;
};
class MonsterBuilder : public CharacterBuilder
{
public:
virtual void buildSkills()
{
int_character->setLockpick(10);
int_character->setSneak(12);
int_character->setGuns(50);
}
virtual void buildAttributes()
{
int_character->setStrength(5);
int_character->setDexterity(5);
int_character->setEndurance(5);
}
};
class RuffianBuilder : public CharacterBuilder
{
public:
virtual void buildSkills()
{
int_character->setLockpick(10);
int_character->setSneak(12);
int_character->setGuns(50);
}
virtual void buildAttributes()
{
int_character->setStrength(5);
int_character->setDexterity(5);
int_character->setEndurance(5);
}
};
class Builder
{
public:
void setBuilder(CharacterBuilder * builder)
{
this->builder = builder;
}
Character * getCharacter()
{
return builder->getCharacter();
}
void buildCharacter()
{
//std::cout << builder->buildSkills;
builder->buildSkills();
builder->buildAttributes();
}
private:
CharacterBuilder * builder;
};
int main()
{
Builder B;
RuffianBuilder R;
MonsterBuilder Mo;
B.setBuilder(&R);
B.buildCharacter();
std::cout << B.getCharacter()->getGuns();
std::cout << B.getCharacter()->getStrength();
B.setBuilder(&Mo);
B.buildCharacter();
//std::cout << B.getCharacter()->getStrength();
return 0;
}
What causes this problem? Could somebody explain it?
Reading uninitlalized variable will cause undefined behavior.
I added builder->buildCharacter(); to Builder::buildCharacter() and then this code seems working well.
class Builder
{
public:
void setBuilder(CharacterBuilder * builder)
{
this->builder = builder;
}
Character * getCharacter()
{
return builder->getCharacter();
}
void buildCharacter()
{
//std::cout << builder->buildSkills;
builder->buildCharacter(); // add this line
builder->buildSkills();
builder->buildAttributes();
}
private:
CharacterBuilder * builder;
};

Inheritance doesn't work when using loop

I have a small problem with inheritance in my code - it suddenly stops working when I add identical code in another "if" statement in my loop.
Here is the code I use for "main.cpp":
#include "bibl.h"
using namespace std;
int main()
{
int o;
Vec2 test;
while(1)
{
cout<<"1. Add item and show."<<endl<<"2. Show."<<endl;
cin>>o;
if(o==1)
{
InhItem a("Test",100);
test.addItem(&a);
cout<<"This show works:"<<endl;
test.getVec1(0)->getItem(0)->Show();//This code works.
}
else if(o==2)
{
cout<<"This show doesn't work:"<<endl;
test.getVec1(0)->getItem(0)->Show();//This doesn't.
}
}
system("pause");
return 0;
}
And the code for "bibl.h":
#ifndef TEST1
#define TEST1
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Item
{
protected:
string im;
string theme;
public:
Item(string im=" ", string theme=" "):im(im),theme(theme)
{
}
~Item()
{
}
string getTheme()
{
return theme;
}
virtual void Show()
{
}
};
class InhItem:public Item
{
int tst;
public:
InhItem(string im=" ", int tst=0):Item(im),tst(tst)
{
}
~InhItem()
{
}
void Show()
{
cout<<tst<<endl;
}
};
class Vec1
{
vector<Item*> Vec1a;
string theme;
public:
Vec1(string theme=" "):theme(theme)
{
}
~Vec1()
{
}
void addToVec1a(Item *item)
{
Vec1a.push_back(item);
}
string getTheme()
{
return theme;
}
Item *getItem(int p)
{
return Vec1a[p];
}
};
class Vec2
{
vector<Vec1*> Vec2a;
public:
Vec2()
{
}
~Vec2()
{
}
void addToVec2(Vec1 *vec1)
{
Vec2a.push_back(vec1);
}
void addItem(Item *item)
{
for(int i=0;i<=Vec2a.size();i++)
{
if(i==Vec2a.size())
{
addToVec2(new Vec1(item->getTheme()));
Vec2a[i]->addToVec1a(item);
break;
}
else if(Vec2a[i]->getTheme().compare(item->getTheme())==0)
{
Vec2a[i]->addToVec1a(item);
break;
}
}
}
Vec1 *getVec1(int r)
{
return Vec2a[r];
}
};
#endif
When I try to use the 2nd "if" after adding the item with 1st, it doesn't show - in 1st "if" test.getVec1(0)->getItem(0)->Show(); works, but in another it doesn't.
What is the cause of this problem and how can I fix it?

Microsoft C++ exception: std::bad_alloc. What could be causing it?

Same code that I was working on last night, has thrown up a whole new error. One that I've never encountered before, and I am at the point of considering throwing things at my PC. But, everyone here was very helpful last night, so I thought I'd see if anyone had any ideas on this new problem.
Something is causing "Microsoft C++ exception: std::bad_alloc" and I think it's within the first line of the main.cpp, but as that is just creating the player as a Hero (child of creature) class. I can't see why it can't do it.
I know it's probably something stupid, that I've done badly ... but any help would be appreciated!
//main.cpp
#include "Creature.h"
#include "Hero.h"
#include "Monster.h"
#include <conio.h>
using namespace std;
int main()
{
Hero player(1);
Monster baddie;
player.setX(1);
player.setY(1);
baddie.setX(20);
baddie.setY(20);
player.Display();
baddie.Display();
baddie.chase(player);
player.Display();
baddie.Display();
_getch();
return 0;
}
===================================
//Creature.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Creature
{
protected:
int m_xpos;
int m_ypos;
string m_name;
public:
Creature(string name, int xpos, int ypos);
void Display(void);
void left(void);
void right(void);
void up (void);
void down(void);
void setX(int x);
void setY(int y);
int getX(void);
int getY(void);
};
===================================
//monster.h
#pragma once
#include "Creature.h"
class Monster : public Creature
{
public:
Monster();
void chase(class Hero);
bool eaten(class Hero);
};
===================================
//Hero.h
#pragma once
#include "Creature.h"
class Hero : public Creature
{
private:
int m_lives;
int m_score;
public:
Hero(int lives);
void Display(void);
void setScore(void);
};
===================================
//creature.cpp
#include "Creature.h"
Creature::Creature(string name, int xpos, int ypos)
{
m_xpos = xpos;
m_ypos = ypos;
m_name = name;
}
void Creature::Display(void)
{
cout << m_name << endl;
cout << m_xpos << endl;
cout << m_ypos << endl;
}
void Creature::left(void)
{
m_xpos = m_xpos+1;
}
void Creature::right(void)
{
m_xpos = m_xpos-1;
}
void Creature::up(void)
{
m_ypos = m_ypos-1;
}
void Creature::down(void)
{
m_ypos = m_ypos+1;
}
void Creature::setX(int x)
{
m_xpos = x;
}
void Creature::setY(int y)
{
m_ypos = y;
}
int Creature::getX(void)
{
return m_xpos;
}
int Creature::getY(void)
{
return m_ypos;
}
===================================
//Hero.cpp
#include "Creature.h"
#include "Hero.h"
Hero::Hero(int lives) : Creature(m_name, m_xpos, m_ypos)
{
m_lives = lives;
}
void Hero::Display(void)
{
Creature::Display();
cout << "Lives: " << m_lives << endl;
cout << "Score: " << m_score << endl;
}
void Hero::setScore(void)
{
m_score = 0;
}
===================================
//Monster.cpp
#include "Creature.h"
#include "Monster.h"
#include "Hero.h"
Monster::Monster() : Creature(m_name, m_xpos, m_ypos)
{
}
void Monster::chase(Hero hero)
{
if(getX() < hero.getX())
{
right();
}
if(getX() > hero.getX())
{
left();
}
if(getX() < hero.getX())
{
down();
}
if(getX() >hero.getX())
{
up();
}
}
bool Monster::eaten(Hero hero)
{
if((getX() == hero.getX())&&(getX() == hero.getX()))
{
return true;
}
}
===================================
The problem lay in Hero::Hero(int lives) : Creature(m_name, m_xpos, m_ypos) and the equivilant with the Monster.cpp file.
Changing them to Hero::Hero(int lives) : Creature("", 0,0) fixed the memory problem.
Thanks again to a wonderful community!
Hopefully, you'll never see this code again! (fingers crossed!)
The error is with this line:
Hero::Hero(int lives) : Creature(m_name, m_xpos, m_ypos)
You cannot create the Creature sub-object by passing its own uninitialized data members to it. You need to pass some sort of valid values to the base-class constructor, like Creature("", 0, 0) for example.
The error is caused, somehow, by the attempt to copy an uninitialized std::string object.