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.
Related
I have following C++ code
Rectangle.h
class Rectangle {
public:
Rectangle(int _id);
void draw();
int getId();
private:
int id;
};
Rectangle.cpp
#include "Rectangle.h"
#include <iostream>
Rectangle::Rectangle(int _id) {
id = _id;
}
void Rectangle::draw() {
std::cout << "Drawing rectangle with id: " << id << std::endl;
}
int Rectangle::getId() {
return id;
}
RectangleCollection.h
#include "Rectangle.h"
class RectanglesCollection {
public:
Rectangle rectangle_00;
Rectangle rectangle_01;
Rectangle rectangle_02;
Rectangle rectangle_03;
RectanglesCollection();
void update();
};
RectangleCollection.cpp
#include "RectanglesCollection.h"
RectanglesCollection::RectanglesCollection() :
rectangle_00(10),
rectangle_01(20),
rectangle_02(30),
rectangle_03(40)
{}
void RectanglesCollection::update()
{
rectangle_00.draw();
rectangle_01.draw();
rectangle_02.draw();
rectangle_03.draw();
}
main.cpp
#include "Rectangle.h"
#include "RectanglesCollection.h"
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
RectanglesCollection rectangles;
rectangles.update();
std::cout << "Id of the first rectangle in collection of rectangles: " << rectangles.rectangle_00.getId() << std::endl;
return 0;
}
My question is whether there is a possibility how I can avoid repeating the code inside the RectanglesCollection::update method and instead of that to use some loop iterating directly above the individual Rectangle members? It would be ideal if the user of the collection need not do anything else than define the instances of the Rectangle class. At the same time I would like to preserve the possibility to work with the Rectangle members individualy like rectangles.rectangle_00.getId().
If you represent your Rectangle member variables instead as a std::array<Rectangle, 4> in your RectanglesCollection, you can then easily access them by index and an operator[](size_t) accessor member function.
#include <array>
#include <cstddef>
#include <iostream>
#include <stdexcept>
using std::array;
using std::cout;
using std::ostream;
using std::out_of_range;
using std::size_t;
// NAME_OF for String-ify.
#define NAME_OF(x) #x
class Rectangle {
int _id;
public:
Rectangle(int id);
void draw(ostream&) const;
auto id() const -> int;
};
Rectangle::Rectangle(int id_) : _id{id_} { }
void Rectangle::draw(ostream& out) const {
out << "Drawing rectangle with id: " << id() << "\n";
}
auto Rectangle::id() const -> int {
return _id;
}
class RectanglesCollection {
array<Rectangle, 4> rectangles = {10, 20, 30, 40};
public:
auto operator[](size_t i) const -> Rectangle;
void display() const;
};
auto RectanglesCollection::operator[](size_t i) const -> Rectangle {
if (i >= rectangles.size())
throw out_of_range(NAME_OF(i));
return rectangles[i];
}
void RectanglesCollection::display() const {
for (auto&& r : rectangles) {
r.draw(cout);
}
}
int main() {
auto rectangles = RectanglesCollection();
rectangles.display();
cout << "Id of the first rectangle in collection of rectangles: " << rectangles[0].id() << "\n";
}
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();
}
How to run a function of an actual object, which is stored in the container using OOP?
Background: I'm writing a game. There is a set of 4 interconnected rooms. There are two different room types and two different player types. Players should run as threads. The Killer should have a fight with a normal player in the Action room. In the second type of room, nothing should happen. The game logic and code is simplified.
When the thread starts, void Player::operator()() is being executed. The player enters the room, does his action initializeAction(), and leaves it. In case of a Killer, his initializeAction() leads to room->actionInRoom(*this), which executes player.inActionRoom().
The problem is in this code void Killer::inActionRoom():
std::vector<Player> &playersWithoutKillers = room->getPlayersWithoutKillers();
auto it = playersWithoutKillers.begin();
std::advance(it, 0);
Player chosenPlayerForFight = *it;
...
chosenPlayerForFight.decreasePoints();
where chosenPlayerForFight.decreasePoints(); does not decrease the points for the actual player, but I think it does it for a copy of an object.
If I run the code, this mistake is visible: OtherPlayer's points will always reset to 1. If I'm decreasing it every time the fight occurs, the negative value is expected.
-> Killer in Forth room Killer 11 vs OtherPlayer 1
Starting decreasing points from 1
Ending decreasing points from 0
I tried to fix the code, mainly by making sure the reference of an object is passed.
Main.cpp:
#include <iostream>
#include <memory>
#include <thread>
#include "Room.h"
#include "Player.h"
std::mutex globalMessageMutex;
int main() {
auto first = std::make_shared<RelaxRoom>("First room");
auto second = std::make_shared<ActionRoom>("Second room");
auto third = std::make_shared<RelaxRoom>("Third room");
auto forth = std::make_shared<ActionRoom>("Forth room");
first->setRoomPair(second, forth);
second->setRoomPair(third, first);
third->setRoomPair(forth, second);
forth->setRoomPair(first, third);
std::vector<std::thread> players;
players.emplace_back(OtherPlayer("OtherPlayer", first));
players.emplace_back(Killer("Killer", first));
for (auto &t : players) {
if (t.joinable()) {
t.join();
}
}
return 0;
}
Player.h
#ifndef HW03_PLAYER_H
#define HW03_PLAYER_H
#include <string>
#include <memory>
class Room;
class Player {
friend class Room;
public:
Player(const std::string &playerName, std::shared_ptr<Room> initialTargetRoom);
void operator()();
friend bool operator== ( const Player &lhs, const Player &rhs );
const std::string &getName() const;
virtual void inActionRoom() {};
virtual void inRelaxRoom(Room &pRoom) {};
virtual bool isKiller()const;
virtual bool isOtherPlayer();
int getPoints()const;
void increasePoints();
void decreasePoints();
int points;
protected:
std::shared_ptr<Room> room;
virtual void initializeAction();
private:
std::string name;
std::shared_ptr<Room> initialRoom;
};
class OtherPlayer : public Player {
public:
OtherPlayer(const std::string &playerName, const std::shared_ptr<Room> &initialTargetRoom);
void initializeAction() override;
void inActionRoom() override;
void inRelaxRoom(Room &pRoom) override;
bool isOtherPlayer() override;
};
class Killer : public Player {
public:
Killer(const std::string &playerName, const std::shared_ptr<Room> &initialTargetRoom);
void initializeAction() override;
void inActionRoom() override;
void inRelaxRoom(Room &pRoom) override;
bool isKiller() const override;
};
#endif //HW03_PLAYER_H
Player.cpp
#include <iostream>
#include <chrono>
#include <thread>
#include <random>
#include "Player.h"
#include "Room.h"
extern std::mutex globalMessageMutex;
Player::Player(const std::string &playerName, std::shared_ptr<Room> initialTargetRoom) {
name = playerName;
initialRoom = initialTargetRoom;
room = initialTargetRoom;
points = 1;
}
void Player::operator()() {
room->enter(*this);
initializeAction();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
room->leave(*this);
while (auto nextRoom = room->getNext()) {
room = nextRoom;
nextRoom->enter(*this);
initializeAction();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
nextRoom->leave(*this);
}
}
void Player::initializeAction() {}
bool operator==(const Player &lhs, const Player &rhs) {
return lhs.name == rhs.name;
}
const std::string &Player::getName() const {
return name;
}
bool Player::isKiller() const {
return false;
}
bool Player::isOtherPlayer() {
return false;
}
int Player::getPoints() const {
return points;
}
void Player::increasePoints() {
points++;
}
void Player::decreasePoints() {
std::cout << "Starting decreasing points from " << points << std::endl;
points--;
std::cout << "Ending decreasing points from " << points << std::endl;
}
OtherPlayer::OtherPlayer(const std::string &playerName, const std::shared_ptr<Room> &initialTargetRoom) : Player(playerName,
initialTargetRoom) {}
void OtherPlayer::initializeAction() {
room->actionInRoom(*this);
}
void OtherPlayer::inActionRoom() {}
void OtherPlayer::inRelaxRoom(Room &pRoom) {}
bool OtherPlayer::isOtherPlayer() {
return true;
}
Killer::Killer(const std::string &playerName, const std::shared_ptr<Room> &initialTargetRoom) : Player(playerName,
initialTargetRoom) {}
void Killer::initializeAction() {
room->actionInRoom(*this);
}
void Killer::inActionRoom() {
std::lock_guard<std::mutex> ml(globalMessageMutex);
if (!room->getPlayersWithoutKillers().empty()) {
**std::vector<Player> &playersWithoutKillers = room->getPlayersWithoutKillers();**
**auto it = playersWithoutKillers.begin();
std::advance(it, 0);
Player chosenPlayerForFight = *it;**
auto killersVitality = this->getPoints();
auto othersPlayerPoints = chosenPlayerForFight.getPoints();
std::cout << "-> Killer in " << room->getName() << " " << this->getName() << " " << killersVitality
<< " vs " << chosenPlayerForFight.getName() << " " << othersPlayerPoints << std::endl;
this->increasePoints();
**chosenPlayerForFight.decreasePoints();**
}
}
void Killer::inRelaxRoom(Room &pRoom) {
}
bool Killer::isKiller() const {
return true;
}
Room.h
#ifndef HW03_ROOM_H
#define HW03_ROOM_H
#include <string>
#include <vector>
#include <condition_variable>
class Player;
class Room {
public:
Room(const std::string &roomName);
void setRoomPair(std::shared_ptr<Room> firstRoom, std::shared_ptr<Room> secondRoom);
std::shared_ptr<Room> getNext();
void enter(Player &player);
void leave(Player &player);
virtual void actionInRoom(Player &player)= 0;
const std::string &getName() const;
const std::vector<Player> &getPlayers();
std::vector<Player> &getPlayersWithoutKillers();
protected:
std::string name;
size_t killersCount;
size_t playersWithoutKillersCount;
private:
std::vector<Player> players;
std::vector<Player> playersWithoutKillers;
std::condition_variable cv;
std::mutex mutex;
std::pair<std::shared_ptr<Room>, std::shared_ptr<Room>> roomPair;
void updateCounterPlayerLeaves(Player &player);
void updateCounterPlayerEnters(Player &player);
};
class ActionRoom : public Room {
public:
ActionRoom(const std::string &roomName) : Room(roomName) {}
void actionInRoom(Player &player) override;
};
class RelaxRoom : public Room {
public:
RelaxRoom(const std::string &roomName) : Room(roomName) {}
void actionInRoom(Player &player) override;
};
#endif //HW03_ROOM_H
Room.cpp
#include <iostream>
#include <algorithm>
#include <random>
#include "Room.h"
#include "Player.h"
#include <mutex>
extern std::mutex globalMessageMutex;
Room::Room(const std::string &roomName) {
name = roomName;
}
const std::string &Room::getName() const {
return name;
}
std::shared_ptr<Room> Room::getNext() {
auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 engine(seed);
std::uniform_int_distribution<int> randomGenerator(0, 1);
auto randomNumber = randomGenerator(engine);
if (randomNumber) {
return roomPair.second;
}
return roomPair.first;
}
void Room::enter(Player &player) {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [this, &player] {
return true;
}
);
players.push_back(player);
updateCounterPlayerEnters(player);
std::lock_guard<std::mutex> ml(globalMessageMutex);
std::cout << name << ": killers: " << killersCount << ", other players: " << playersWithoutKillersCount <<
std::endl;
}
void Room::updateCounterPlayerEnters(Player &player) {
if (player.isKiller()) {
killersCount++;
} else {
playersWithoutKillersCount++;
playersWithoutKillers.push_back(player);
}
}
void Room::leave(Player &player) {
{
std::lock_guard<std::mutex> lock(mutex);
auto it = std::find(players.begin(), players.end(), player);
if (it == players.end()) {
return;
}
players.erase(it);
updateCounterPlayerLeaves(player);
}
cv.notify_all();
}
void Room::updateCounterPlayerLeaves(Player &player) {
if (player.isKiller()) {
killersCount--;
} else {
playersWithoutKillersCount--;
auto it = std::find(playersWithoutKillers.begin(), playersWithoutKillers.end(), player);
if (it == playersWithoutKillers.end()) {
return;
}
playersWithoutKillers.erase(it);
}
}
void Room::setRoomPair(std::shared_ptr<Room> firstRoom, std::shared_ptr<Room> secondRoom) {
roomPair.first = std::move(firstRoom);
roomPair.second = std::move(secondRoom);
}
const std::vector<Player> &Room::getPlayers() {
return players;
}
std::vector<Player> &Room::getPlayersWithoutKillers() {
return playersWithoutKillers;
}
void ActionRoom::actionInRoom(Player &player) {
player.inActionRoom();
}
void RelaxRoom::actionInRoom(Player &player) {
player.inRelaxRoom(*this);
}
Not a complete answer, since you said this is a homework assignment.
However, one pattern you can use to solve this problem is to have your container store std::unique_ptr<some_base_class> values, or if necessary std::shared_ptr<some_base_class>, and fill them with pointers to derived objects. For example: container.emplace_back(static_cast<some_base_class*>(new derived_class(foo, bar, baz))); will construct everything in place inside your container, so the compiler doesn’t need to make any temporary copies. You might also write something like:
std::vector<std::unique_ptr<some_base_class>> container;
{
std::unique_ptr<derived_class> temp =
make_unique<derived_class>();
temp->setup( foo, bar, baz );
container.emplace_back(static_cast<some_base_class*>(temp.release()));
// temp is now empty, and the pointer in the container now owns the object.
}
You can use the full interface of some_base_class through these smart pointers, with ->, but if you need to turn them back into references to derived objects, you would use RTTI and dynamic_cast.
There are other approaches, including a discriminated union and std::variant, but storing smart pointers to the base class that defines your interface is what I recommend you try here.
I'm new to C++ and I'm practicing inheritance and I typed the code below. In Squirtle.cpp, visual studio is telling me that newHp, newLevel, newExperience and newAttack are all undefined. Why is this the case? How do I fix it? I've looked up other examples here such as this but I guess they would't get an error because both their base and child constructors are in the same file?
****Pokemon.h****
#ifndef _POKEMON_
#define _POKEMON_
#include <string>
#include <iostream>
using namespace std;
class Pokemon {
//Members
private:
int hp;
int level;
int experience;
int attack;
//Member functions
public:
Pokemon(int newHp, int newLevel, int newExperience, int newAttack);
virtual ~Pokemon();
int getHp();
int getAttack();
void setHp(int newHp);
void setAttack(int newAttack);
void physicalAttack(Pokemon &target);
};
#endif
****Pokemon.cpp****
#include "Pokemon.h"
Pokemon::Pokemon(int newHp, int newLevel, int newExperience, int newAttack)
{
hp = newHp;
level = newLevel;
experience = newExperience;
attack = newAttack;
}
Pokemon::~Pokemon()
{
}
int Pokemon::getHp()
{
return hp;
}
int Pokemon::getAttack()
{
return attack;
}
void Pokemon::setHp(int newHp)
{
hp = newHp;
}
void Pokemon::setAttack(int newAttack)
{
attack = newAttack;
}
void Pokemon::physicalAttack(Pokemon &target)
{
target.setHp(target.getHp() - getAttack());
cout << "Dealt " << getAttack() << "damages to target! Hp is now at " << target.getHp() << "!";
}
****Squirtle.h****
#include "Pokemon.h"
#ifndef _SQUIRTLE_
#define _SQUIRTLE_
class Squirtle :Pokemon{
//members
private:
int mana;
//member functions
public:
Squirtle(int newMana);
int getMana();
void setMana(int newMana);
void freeze(Pokemon &target);
};
#endif
****Squirtle.cpp****
#include "Squirtle.h"
Squirtle::Squirtle(int newMana):Pokemon(newHp, newLevel, newExperience, newAttack)
{
mana = newMana;
}
int Squirtle::getMana()
{
return mana;
}
void Squirtle::setMana(int newMana)
{
mana = newMana;
}
void Squirtle::freeze(Pokemon &target)
{
setMana(getMana() - 1);
target.setAttack(0);
cout << "Squirtle has frozen the target! Its attack is now reduced to 0!";
}
In this constructor definition
Squirtle::Squirtle(int newMana):Pokemon(newHp, newLevel, newExperience, newAttack)
{
mana = newMana;
}
identifiers newHp, newLevel, newExperience, newAttack are not declared. So the compiler does not know for example what is newHp
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.