Cannot access memory at address 0x1 - c++

I have three base Classes {Player,Weapon,Game} and one inherited Class Warrior from Player. The code I added may not be minimal but I added anything that can be relevant. Since I didn't know where to look.
This is my test for simple debugging, I add Players into vectorPlayers which is definded in game.h
int main() {
Weapon w1("hello",STRENGTH,3);
Game game(3);
game.addWarrior("s22","we",STRENGTH,3,55);
//4
game.addWarrior("s22","we",STRENGTH,3,55);
return 0;
}
When I reach the the 4th line, vectorPlayers[0] includes the correct inputs. But when I enter to game.cpp and call the function addPlayer in addWarrior,suddenly players_name for example switches to
error: Cannot access memory at address 0x1
//inside game.cpp
GameStatus Game::addPlayer(const string playerName, const string weaponName,
Target target,int hit_strength)
{
Weapon newWeapon(weaponName,target,hit_strength);
Warrior newWarrior(playerName,newWeapon,false);
if(ifNameAlreadyExists(playerName)) {
addRegPlayer(static_cast<Player*>(&newWarrior));
}
return SUCCESS;
}
GameStatus Game::addRegPlayer(Player* player)
{
playersVector.push_back(player);
}
//base classes
class Game {
private:
int maxPlayer;
vector<Player*> playersVector;
}
class Player {
string player_name;
int level;
int strength;
Weapon player_weapon;
protected:
int place;
int life;
public:
Player(const string &name, const Weapon &weapon);
virtual ~Player();
}
//inherited class
class Warrior : public Player {
private:
bool rider;
public:
Warrior ();
Warrior (string const& name, Weapon const& weapon, bool rider);
~ Warrior () override = default;
Warrior &operator=(const Warrior &warrior) ;
Warrior ( const Warrior &warrior) = default;
void makeStep() override;
};
//Constructor of Warrior
Warrior::Warrior(string const& name, Weapon const& weapon, bool rider) :
Player(name,weapon),rider(rider){
if (weapon.getTarget() == LEVEL){
throw IllegalWeapon();
}
}
//constructor of player
Player::Player(const string& name, const Weapon& weapon) :
level(1),life(1),strength(1),player_weapon(weapon),player_name(name),place(0){
}

Related

How to set BaseClass variable from DerivedClass parameter

I have the classes Player and HumanPlayer. HumanPlayer is derived from Player.
class Player {
private:
int id;
protected:
string name;
public:
Player(int id);
~Player();
}
class HumanPlayer : public Player {
public:
HumanPlayer(int id, string name);
}
I want to make a constructor for HumanPlayer the set the Player id and name but I don't seem to figure out how to set Player::id to the HumanPlayer::id.
This is what I have worked out but gives an error
"int Player::id' is private within this context"
HumanPlayer::HumanPlayer(int id, string name) : Player(id){
this -> id = id;
this -> name = name;
}
For your understanding.
class Player {
private:
int id;
protected:
std::string name;
public:
//Base class constructor, initialize Id.
Player(int i):id(i)
{}
~Player() {}
//Test
int GetId()
{
return id;
}
std::string GetName()
{
return name;
}
};
class HumanPlayer : public Player {
public:
HumanPlayer(int i, std::string s) :Player(i) //Pass on Id base class constructor
{
name = s; //Protected variable accessible.
}
};
void main()
{
HumanPlayer hPlayer(10, "Test");
std::cout << hPlayer.GetId() << std::endl;
std::cout << hPlayer.GetName() << std::endl;
}

can someone please explain what is wrong in this c++ code and provide a solution

I have declared a class Products and another class CD the class CD is inheriting the class Products.
Now I have declared an constructor to update the value of the. and I am getting an error
#include <iostream>
#include <string>
class Products
{
private:
std::string name;
std::string type;
double price;
public:
virtual std::string getname();
virtual double getprice();
virtual void show();
std::string gettype()
{
return type;
}
};
class CD: public Products
{
private:
std::string artist;
std::string studio;
public:
CD(std::string sname,double sprice,std::string sartist,std::string sstudio)
{
this->type = "CD";
this->name = sname ;
this->price = sprice;
this->artist = sartist;
this->studio = sstudio;
}
void show()
{
std::cout<<"\nName of the CD:\t"<<this->name;
std::cout<<"\nArtist of the CD:\t"<<this->artist;
std::cout<<"\nStudio of the CD:\t"<<this->studio;
std::cout<<"\nPrice of the cd:\t"<<this->price;
}
};
int main()
{
CD obj("Oceans",49,"somesinger","somestudio");
}
ERROR :
In constructor 'CD::CD(std::string, double, std::string)';
'std::string Products::type' is private within this context
this->type="CD";
'std::string Products::name' is private within this context
this->name=sname;
'double Products::price' is private within this context
this->price= sprice;
Basically it is not giving error for the private data members of the CD class but just the data members that are being inherited from Products Class
#include <iostream>
#include <string>
class Products
{
private:
std::string m_name;
std::string m_type;
double m_price;
public:
// No need for your setters/getters to be virtual
// if the derived class won't override anything or not
const std::string& getType() const { return m_type; }
const std::string& getName() const { return m_name; }
double getPrice() const { return m_price; }
void setType(const std::string& new_type) { m_type = new_type; }
void setName(const std::string& new_name) { m_name = new_name; }
void setPrice(double new_price) { m_price = new_price; }
// Force derived class to override function
virtual void show() = 0;
};
class CD: public Products
{
private:
std::string artist;
std::string studio;
public:
CD(std::string sname,double sprice,std::string sartist,std::string sstudio)
{
this->setType("CD");
this->setName(sname) ;
this->setPrice(sprice);
this->artist = sartist;
this->studio = sstudio;
}
void show()
{
std::cout<<"\nName of the CD:\t"<<this->getName();
std::cout<<"\nArtist of the CD:\t"<<this->artist;
std::cout<<"\nStudio of the CD:\t"<<this->studio;
std::cout<<"\nPrice of the cd:\t"<<this->getPrice();
}
};
int main()
{
CD obj("Oceans",49,"somesinger","somestudio");
obj.show();
}
I want you to understand some changes here. First the removal of virtual keyword. In your case the setters/getters had no need to be virtual, as they were not being overriden or didn't have a need to be based on the current example. Second, the setters/getters are setup to access the private members accordingly. We now use these functions within class CD. Also we changed the function show() to be pure virtual notice the = 0 at the end. I added a comment saying this forces derived classes to override the function. Lastly, your main wasn't doing anything so I added a obj.show() to actually print something.
In this solution, I've added a constructor for Products, and CD's constructor calls it to initialize the members that are private to Products.
I removed the virtual on getName and getPrice since these features don't change other products.
show remains virtual, and I split it into a piece in Products and a piece in CD so they each display their respective fields. This separates the printing according to where the variables are, so for example, another class derived from Products wouldn't have to reimplement printing of name and price.
#include <iostream>
#include <string>
class Products
{
private:
std::string name;
std::string type;
double price;
public:
std::string getname(); // Does not need to be virtual, as it's not overriden
double getprice(); // Also does not need to be virtual
virtual void show() const {
std::cout<<"\nName of the " << type << ":\t"<<this->name;
std::cout<<"\nPrice of the " << type << ":\t"<<this->price;
};
Products (const std::string &stype, double sprice, const std::string &sname)
: name (sname), type (stype), price (sprice) {
}
std::string gettype() const
{
return type;
}
};
class CD: public Products
{
private:
std::string artist;
std::string studio;
public:
CD(const std::string &sname,double sprice, const std::string &sartist, const std::string &sstudio)
: Products ("CD", sprice, sname)
{
artist = sartist;
studio = sstudio;
}
void show() const override
{
Products::show(); // Call parent show() to show the basics
std::cout<<"\nArtist of the " << gettype() << ":\t"<<this->artist;
std::cout<<"\nStudio of the " << gettype() << ":\t"<<this->studio;
}
};
int main()
{
Products shoe ("Shoe", 3.49, "Nike runner");
shoe.show();
CD obj("Oceans",49,"somesinger","somestudio");
obj.show();
}

How to change attributes based on objects in vector?

This is the situation:
a Player class with statistics as variables.
a Keeper class derived from Player.
an Action class
a Run class derived from Action
the player class has vector<Action*>
I don't understand how i can implement the following functionality:
iterate through the vector and based on the action, update the correct attribute in Player or Keeper (numberOfRunKm and numberOfSaves)
class Action {
public:
Action();
virtual ~Action();
virtual void write();
};
class Run: public Action {
double runKm;
public:
Run(double runKm);
~Run();
double getRunKm() const;
void setRunKm(double runKm);
void write();
};
class Save: public Action {
public:
Save();
~Save();
void write();
};
class Player {
string name;
vector<Action*> actions;
double numberOfRunKm = 0.0;
public:
Player(const string &name);
~Player();
virtual void write();
void run();
void addAction(Action* action);
void updateStatistics();
};
class Keeper: public Player {
int numberOfSaves = 0;
public:
Keeper(const string &name);
~Keeper();
void write();
void save();
};

Using polymorphism to copy derived class' value to the base class

English is not my first language. I hope I will not make lot of mistakes. I'll try my best to be as clear as possible!
I have a base class
class engine
{
private :
std::string name;
double weight;
public:
engine();
~engine();
std::string getName() const;
int getWeight() const
};
std::string engine::getName() const{
return this->name;
}
int engine::getWeight() const{
return this->weight;
}
and derived class
class diesel : public engine
{
private:
std::string name;
double weight;
public:
diesel();
~diesel();
};
diesel::diesel(){
this->name = Diesel;
this->weight = 500.00;
}
In my main.cpp
int main()
{
diesel diesel_engine;
const engine &e = diesel_engine;
std::cout<<e.getWeight()<<e.getName()<<std::endl;
return 0;
}
1- I must construct a diesel class named diesel_engine.
2- pass diesel_engine's value to a new engine by reference??
When I call const engine &e = diesel_engine;, diesel_engine's value(name and weight) should be copied to the new engine e.
So 'e' should have weight of 500.00 and the name "Diesel".
I don't get how can I use polymorphism to do that.
Thank you for reading this question!
Lets start with the class declarations
class Engine
{
private:
float weight_;
std::string name_;
public:
Engine(float weight, std::string name) : weight_(weight), name_(name){};
std::string GetName() const { return name_;}
};
class Diesel : public Engine
{
public:
Diesel(float weight, std::string name) : Engine(weight, name){}
};
So what we have here is an Engine class which is our base class and then we define our Diesel class, Diesel inherits from Engine and passes the arguments to its base class.
Now to use this:
Diesel disel_engine(0.0, "diesel engine");
const Engine& eng = disel_engine;
cout << eng.GetName();
The call to eng.GetName() prints the correct engine name
Demo Here

Void pointer to class error

class Hero
{
public:
Hero();
virtual int useAbility(){}
virtual int basicAttack(){}
int getHitPoints();
int getManaPoints();
void setHitPoints(int x);
void setManaPoints(int x);
protected:
unsigned int hitPoints;
unsigned int manaPoints;
private:
friend void printHero();
};
class Mage : public Hero
{
public:
Mage();
int useAbility();
int basicAttack();
std::string getClassName();
protected:
private:
std::string className;
};
Same for Warrior
int input;
void *actor;
cin >> input;
if(input == 1) actor = new Warrior;
if(input == 2) actor = new Mage;
printHero(actor.getClassName(),actor.getHitPoints(),actor.getManaPoints());
So i declare the pointer 'actor' , and I want it to become a pointer to a class, but apparently it does not work.
I get this error
request for member 'getClassName' in 'actor', which is of non-class type 'void*'
Warrior and Mage have the parent class person.
you want to do:
person *actor;