c++ Error error C2512 no appropriate default constructor available - c++

I am trying to implement a card game in c++ using VS-2013, and I have a "Player" class.
The "Player" class is abstract in the sense that no actual objects of that class are to be initialized. Instead, it is only there to be inherited to 4 different player classes (with 4 different playing strategies) - "PlayerType1" to "PlayerType4".
This is my Player.h file:
#ifndef PLAYER_H_
#define PLAYER_H_
#include <iostream>
#include "Hand.h"
using namespace std;
class Player : public Hand {
private:
const string name;
protected:
Hand myHand;
public:
string getName(); //Returns the name of the player
virtual int getShapeToAsk() = 0;
virtual int getPlayerToAsk() = 0;
virtual ~Player();
};
class PlayerType1 : public Player { //For strategy 1
PlayerType1();
virtual int getShapeToAsk() override;
virtual int getPlayerToAsk() override;
~PlayerType1();
};
class PlayerType2 : public Player { //For strategy 2
PlayerType2();
virtual int getShapeToAsk() override;
virtual int getPlayerToAsk() override;
~PlayerType2();
};
class PlayerType3 : public Player { //For strategy 3
private:
int myNumber, numOfPlayers, nextPlayer;
public:
PlayerType3(int myNumber, int numOfPlayers);
virtual int getShapeToAsk() override;
virtual int getPlayerToAsk() override;
~PlayerType3();
};
class PlayerType4 : public Player { //For strategy 4
private:
int myNumber, numOfPlayers, nextPlayer;
public:
PlayerType4(int myNumber, int numOfPlayers);
virtual int getShapeToAsk() override;
virtual int getPlayerToAsk() override;
~PlayerType4();
};
#endif
And this is my Player.cpp file:
#include <iostream>
#include <vector>
#include "Hand.h"
#include "Player.h"
using namespace std;
//Player functions
string Player::getName(){
return (this->name + " " + this->toString());
}
Player::~Player(){}
//PlayerType1 functions
PlayerType1::PlayerType1(){}
int PlayerType1::getShapeToAsk(){
int maxCount = 0, maxValue, currValue, count;
for (std::vector<Card*>::reverse_iterator i = this->myHand.getCards().rbegin(); i != this->myHand.getCards().rend(); i++){
count = 1;
currValue = (**i).getValue();
for (i; (i != this->myHand.getCards().rend()) && ((**i).getValue() == currValue); ++i){
count++;
}
if (count > maxCount){
maxCount = count;
maxValue = currValue;
if (maxCount == 4) // no need to look at the rest of the hand
break;
}
}
return maxValue;
}
int PlayerType1::getPlayerToAsk(){ return -1; } //-1 means "I am a player of type 1 or 2". Game's responsibility to change later.
PlayerType1::~PlayerType1(){}
//PlayerType2 functions
PlayerType2::PlayerType2(){}
int PlayerType2::getShapeToAsk(){
int minCount = 5, minValue, currValue, count;
for (std::vector<Card*>::iterator i = this->myHand.getCards().begin(); i != this->myHand.getCards().end(); i++){
count = 1;
currValue = (**i).getValue();
for (i; (i != this->myHand.getCards().end()) && ((**i).getValue() == currValue); ++i){
count++;
}
if (count < minCount){
minCount = count;
minValue = currValue;
if (minCount == 1) // no need to look at the rest of the hand
break;
}
}
return minValue;
}
int PlayerType2::getPlayerToAsk(){ return -1; } //-1 means "I am a player of type 1 or 2". Game's responsibility to change later.
PlayerType2::~PlayerType2(){}
//PlayerType3 functions
PlayerType3::PlayerType3(int myNumber, int numOfPlayers){
this->myNumber = myNumber;
this->numOfPlayers = numOfPlayers;
if (myNumber == 1) this->nextPlayer = 2;
else this->nextPlayer = 1;
}
int PlayerType3::getShapeToAsk(){
int maxCount = 0, maxValue, currValue, count;
for (std::vector<Card*>::reverse_iterator i = this->myHand.getCards().rbegin(); i != this->myHand.getCards().rend(); i++){
count = 1;
currValue = (**i).getValue();
for (i; (i != this->myHand.getCards().rend()) && ((**i).getValue() == currValue); ++i){
count++;
}
if (count > maxCount){
maxCount = count;
maxValue = currValue;
if (maxCount == 4) // no need to look at the rest of the hand
break;
}
}
return maxValue;
}
int PlayerType3::getPlayerToAsk(){
int temp = this->nextPlayer;
this->nextPlayer++;
while ((this->nextPlayer == this->myNumber) || (this->nextPlayer > this->numOfPlayers)){
if (this->nextPlayer == this->myNumber) this->nextPlayer++;
if (this->nextPlayer > this->numOfPlayers) this->nextPlayer = 1;
}
return temp;
}
PlayerType3::~PlayerType3(){}
//PlayerType4 functions
PlayerType4::PlayerType4(int myNumber, int numOfPlayers){
this->myNumber = myNumber;
this->numOfPlayers = numOfPlayers;
if (myNumber == 1) this->nextPlayer = 2;
else this->nextPlayer = 1;
}
int PlayerType4::getShapeToAsk(){
int minCount = 5, minValue, currValue, count;
for (std::vector<Card*>::iterator i = this->myHand.getCards().begin(); i != this->myHand.getCards().end(); i++){
count = 1;
currValue = (**i).getValue();
for (i; (i != this->myHand.getCards().end()) && ((**i).getValue() == currValue); ++i){
count++;
}
if (count < minCount){
minCount = count;
minValue = currValue;
if (minCount == 1) // no need to look at the rest of the hand
break;
}
}
return minValue;
}
int PlayerType4::getPlayerToAsk(){
int temp = this->nextPlayer;
this->nextPlayer++;
while ((this->nextPlayer == this->myNumber) || (this->nextPlayer > this->numOfPlayers)){
if (this->nextPlayer == this->myNumber) this->nextPlayer++;
if (this->nextPlayer > this->numOfPlayers) this->nextPlayer = 1;
}
return temp;
}
PlayerType4::~PlayerType4(){}
I get the following errors:
Error error C2512: 'Player' : no appropriate default constructor available <PATH>\player.cpp
A total of 4 errors of that type, each pointing to the constructors of PlayerType1 to PlayerType4.
When I add an empty default constructor to my "Player" class, it solves the problem and I get a successful build.
However, I fail to see why I need to define a default constructor for the "Player" class, as I never initialize an object of that class.
I should also mention I have another class in my project ("Card" class) that is abstract and is just there to be inherited by other classes ("FigureCard" and "NumericCard"), and also has no constructor, and the derived classes have their own constructors, and that causes no error. I fail to see the difference.
I searched other questions, but they all relate to cases in which a default constructor was not defined, and an initialization was attempted of that class elsewhere in the code. That is not my case since I am not initializing an object of class "Player", only the 4 derived classes.
Please help!
Thank you in advance.

Even if your Player class is abstract, you must define a constructor because your class has members. When you create an instance of a derived class (any of your PlayerType) class, it will call the constructor of the base class. This is how inheritence works...
In that case, make it protected (making it public would be useless anyway because it's a pure virtual class).

Your Player class has a private: const string name; member. Look at your Card class; I bet it does not have such a member. That's the difference.
The thing is, the const string name; member must somehow be initialized, and since it is private, it must be initialized within the Player class. (Language rules prohibit the initialization of a private member of a class from a derived class.) Therefore, the Player class must have a constructor which will initialize the name member. The empty constructor achieves this.

Related

C++ GetAsyncKeyState() with private overridden attributes

I am trying to figure out how to use GetAsyncKeyState with private attributes forward and backwards from a base class. I need to be able to reset GetAsyncKeyState to other keypresses. Any idea?
Maybe overriding forward and backwards with other keypresses?
#include <iostream>
#include <windows.h>
#include <string>
#include<conio.h>
using namespace std;
bool reset_defaults = false;
class Base {
protected: // OR private
int forward = VK_UP, backwards = VK_DOWN;
public: //...
}
////////////
class Move : public Base {
public:
Base def;
int move() {
while (true) {
if (GetAsyncKeyState(forward) < 0){
cout << ("forward >>>\n");
if (GetAsyncKeyState(forward) == 0){
cout << ("Stopped\n");
}
}
if (GetAsyncKeyState(VK_SPACE) < 0){break;}
}
}
int main() {
Move move;
move.move();
}
Sorry, but I don't think I understand the whole logic of this yet.
PS UPDATE:
How can I override baseKeys values:
class MovementKeys {
protected:
int baseKeys(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right){
default_key_forward = VK_UP;
default_key_backward = VK_DOWN;
default_key_left = VK_LEFT;
default_key_right = VK_RIGHT;
}
public:
int definedCommand(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right) {
while (reset_defaults == false)
{
cout << ("HERE 1 \n");
if (GetAsyncKeyState(default_key_forward) < 0)
{
cout << ("forward\n");
}
if (GetAsyncKeyState(default_key_backward) < 0)
{
court << ("backwards\n");
}
if (GetAsyncKeyState(default_key_left) < 0)
{
cout << ("left\n");
}
if (GetAsyncKeyState(default_key_right) < 0)
{
cout << ("right\n");
}
if (GetAsyncKeyState(VK_SPACE) < 0) { break; }
}
return 0;
}
int derived_newKeys(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right) {
return baseKeys(default_key_forward, default_key_backward, default_key_left, default_key_right);
}
You probably want to use member variables to store the keys. Instead of deriving the class with new keys, you set the variables in constructors (to default or to changed values) and can also change the key assignment later on.
You probably want to create a separate class, which reacts on the events.
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
class World {
public:
void forward() { y--; };
void backward() { y++; };
void left() { x--; };
void right() { x++; };
private:
int x = 0;
int y = 0;
};
class MovementKeys {
// member variables
private:
// keep reference to world instead of copy; main() has to make sure World object outlives MovementKeys object
World& world;
int key_forward;
int key_backward;
int key_left;
int key_right;
public:
// constructor, which only sets world, but keeps the keys at their default settings
//
// world has to be initialized before the constructor function body
// as references have no default value
// put initialization in member initialization list
MovementKeys(World& w) : world(w)
{
key_forward = VK_UP;
key_backward = VK_DOWN;
key_left = VK_LEFT;
key_right = VK_RIGHT;
}
// constructor which modifies keys
MovementKeys(World& w, int change_key_forward, int change_key_backward, int change_key_left, int change_key_right) : world(w)
{
changeKeys(change_key_forward, change_key_backward, change_key_left, change_key_right);
}
// command loop controlled by keys
int definedCommand()
{
while (true)
{
cout << ("HERE 1 \n");
if (GetAsyncKeyState(key_forward) < 0)
{
cout << ("forward\n");
world.forward();
}
if (GetAsyncKeyState(key_backward) < 0)
{
cout << ("backwards\n");
world.backward();
}
if (GetAsyncKeyState(key_left) < 0)
{
cout << ("left\n");
world.left();
}
if (GetAsyncKeyState(key_right) < 0)
{
cout << ("right\n");
world.right();
}
// optionally change keys from within while loop
if (GetAsyncKeyState(VK_BACK) < 0)
{
key_forward = VK_RETURN;
}
if (GetAsyncKeyState(VK_SPACE) < 0)
{
break;
}
}
return 0;
}
// function for changing the keys stored in the member variables
// can be called by constructor or externally
void changeKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right)
{
key_forward = change_key_forward;
key_backward = change_key_backward;
key_left = change_key_left;
key_right = change_key_right;
}
};
int main()
{
World earth;
// use default keys, declares local variable and constructs MovementKeys object called move
MovementKeys move(earth);
move.definedCommand();
// use custom keys, share same world, declares local variable and constructs MovementKeys object called move2
// static_cast<int>() with a letter in a literal char parameter works, because the VK_ values of letter keys are the actual ASCII values (on purpose by Microsoft, I would assume)
MovementKeys move2(earth, static_cast<int>('W'), static_cast<int>('S'), static_cast<int>('A'), static_cast<int>('D'));
move2.definedCommand();
// change keys in move2
move2.changeKeys(VK_LBUTTON, VK_RBUTTON, VK_CONTROL, VK_SHIFT);
move2.definedCommand();
// run first one again for the fun of it
move.definedCommand();
}
Alternatively passing World& only, where it is used in definedCommand (and at the same time be able to use several worlds):
class World {
// ...
};
class MovementKeys {
// member variables without world, we can also put default value here
private:
int key_forward = VK_UP;
int key_backward = VK_DOWN;
int key_left = VK_LEFT;
int key_right = VK_RIGHT;
public:
// default constructor with no parameters, delegate to other constructor
// delegating not necessary, as the default values are set above anyway; just demonstrating various techniques for initializing member variables
MovementKeys() : MovementKeys(VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT) {};
// constructor which modifies keys, put everything in member initialization list
MovementKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right) : key_forward(change_key_forward), key_backward(change_key_backward), key_left(change_key_left), key_right(change_key_right) {};
// command loop controlled by keys, pass World& here as parameter
int definedCommand(World& world)
{
while (true)
{
// ...
}
return 0;
}
void changeKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right)
{
// ...
}
};
int main()
{
// use default keys, declares local variable and constructs MovementKeys object called move
MovementKeys move;
// use custom keys, declares local variable and constructs MovementKeys object called move2
MovementKeys move2(static_cast<int>('W'), static_cast<int>('S'), static_cast<int>('A'), static_cast<int>('D'));
MovementKeys defaultMenuKeys;
World earth;
World moon;
World menu; // between moving in worlds, we want to control some settings in a menu
move.definedCommand(earth);
move2.definedCommand(earth);
move2.definedCommand(moon);
// change keys in move2
move2.changeKeys(VK_LBUTTON, VK_RBUTTON, VK_CONTROL, VK_SHIFT);
move2.definedCommand(earth);
defaultMenuKeys.definedCommand(menu);
// run first one again for the fun of it
move.definedCommand(moon);
}
You can introduce a (class) enum with a list of the states, why definedCommand() returns:
// outside or can be put into MovementKeys and henceforth used as MovementKeys::ReturnReason
class enum ReturnReason { EXIT, NEWKEYS, SHOWMENU, SWITCHWORLD };
// in class MovementKeys
ReturnReason definedCommand() {
// ...
return NEWKEYS;
// ...
return EXIT;
// ...
return SHOWMENU;
// ...
}
// in main()
ReturnReason r = definedCommand();
if (r == NEWKEYS)
move2.changeKeys(...);
else if (r == EXIT)
return 0;
If you use that 'trick' to also control the menu, it could make sense to use virtual inheritance now for World. As the normal World and the menu World probably react quite differently. (The base class (ancestor) would be World, which is recognized by MovementKeys. Your actual Worlds are objects of derived (children) classes, with more specific behaviour.
definedCommand then can be called and run with any derived class of the base class World.

C++ - Changing class to use virtual functions

I am looking to make this more efficient, how would I Re-write the Enemy class to use inheritance and virtual functions? Including any new child classes.
class Enemy
{
public:
int type; // 0 = Dragon, 1 = Robot
int health; // 0 = dead, 100 = full
string name;
Enemy();
Enemy(int t, int h, string n);
int getDamage(); // How much damage this enemy does
};
Enemy::Enemy() : type(0), health(100), name("")
{ }
Enemy::Enemy(int t, int h, string n) :
type(t), health(h), name(n)
{ }
int Enemy::getDamage() {
int damage = 0;
if (type == 0) {
damage = 10; // Dragon does 10
// 10% change of extra damage
if (rand() % 10 == 0)
damage += 10;
}
else if (type == 1) {
// Sometimes robot glitches and does no damage
if (rand() % 5 == 0)
damage = 0;
else
damage = 3; // Robot does 3
}
return damage;
}
This calculates how much total damage the band will dish out.
int calculateDamage(vector<Enemy*> bandOfEnemies)
{
int damage = 0;
for (int i = 0; i < bandOfEnemies.size(); i++)
{
damage += bandOfEnemies[i]->getDamage();
}
return damage;
}
That's a good start, but with inheritance, you don't need to be so specific. For example, in the enemy class you have an attribute type. If you want to use inheritance, you don't need to specify the type, because the derived class would be the type.
As for your function getDamage(), you can leave it blank and turn it into a virtual function. Putting all of this together, your code should look something like this:
class Enemy
{
public:
int health; // 0 = dead, 100 = full
string name;
Enemy();
Enemy(int t, int h, std::string n);
virtual int getDamage() = 0; // pure virtual function
};
Enemy::Enemy()
: type(0), health(100), name("") {}
Enemy::Enemy(int t, int h, std::string n)
: type(t), health(h), name(n) {}
// class 'Dragon' inherits from class 'Enemy'
class Dragon : public Enemy
{
public:
Dragon() {}
int getDamage()
{
// dragon's damage
}
};
Notice how if you want to create another enemy, you just inherit from the Enemy class. And this way, you can store your characters in an array like this:
vector<Enemy> enemies = {
Dragon(),
Dragon(),
Robot()
};

How to use classes inside another class function independently of where it is declared in C++?

I'm trying to create a Monopoly game in C++ and I've been messing with object-oriented-programming, the problem happens with the classes "Game" and "Player", I would like to know how to use "Game"'s functions inside "Player" and "Player"'s functions inside "Game", but I've been getting a compiler error saying that the class is not defined.
Switching class positions won't work (obviously) but I tried anyways.
Code (reduced and minimized to the Game and Player classes):
namespace Monopoly {
typedef enum { normal, train, company, incometax, luxurytax, start, chancecard, chestcard, jail } type;
class Game {
private:
bool running = false;
int turn = 1;
int currentPlayerID;
int startingMoney = 1000;
std::vector<Player> players;
public:
// Functions
void createPlayer() {
++currentPlayerID;
Player newPlayer(currentPlayerID, startingMoney);
players.push_back(newPlayer);
++currentPlayerID;
}
void createPlayers(int playerAmount) {
for (int i = 0; i <= playerAmount; ++i) {
createPlayer();
}
}
Player getPlayer(int index) {
Player p = players[index];
return p;
}
};
class Player {
private:
int playerID;
int money;
std::vector<int> propertiesOwned;
void addProperty(int id) {
this->propertiesOwned.push_back(id);
}
public:
// Constructor
Player(int pID, int sMoney) {
this->playerID = pID;
this->money = sMoney;
}
// Functions
Player payMoney(int payAmount, unsigned int destinationID, Game engine) {
this->money -= payAmount;
if (destinationID > 0) {
// Checks if you're paying to a player or bank
bool playerFound = false;
for (int i = 0; i <= engine.getPlayerAmount(); ++i) {
if (engine.getPlayer(i).getID() == destinationID) {
playerFound = true;
break;
}
}
if (playerFound) {
// Player was found
engine.getPlayer(destinationID).giveMoney(payAmount);
return;
}
else {
std::cout << "\nERROR: Invalid player ID at function payMoney\n";
return;
}
}
else {
// You're paying to the bank
}
return;
}
void buyProperty(int id, int price, Game engine) {
payMoney(price, 0, engine);
addProperty(id);
}
void giveMoney(int payMoney) {
this->money += payMoney;
}
// Returns
inline int getMoney() { return this->money; }
inline int getID() { return this->playerID; }
inline auto getProperties(int index) {
auto p = propertiesOwned[index];
return p;
}
inline int getPropertyAmount() {
int amount = std::size(propertiesOwned);
return amount;
}
};
}
I expected the classes to run the other classes function normally, but it seens like that in C++, classes are defined in certain order, and you can only access classes (in a class) declared before the class you're using, feedback and alternatives that fix this would help
You are correct that in C++ declaration order matters, and that is the cause of your errors, however there are a few other issues with the code.
Firstly, you should swap the order that Game and Player are defined. This will make it easier, as Player relies on Game fewer times than Game relies on Player.
Next, add a forward declaration for Game before the definition of Player:
class Game;
This tells the compiler that a class named Game exists and allows you to use it in scenarios where it doesn't need to know the contents (i.e. definition) of the class.
Next, make payMoney and buyProperty accept their engine parameter by reference instead of by value by changing the parameter specifier to Game &engine. This is important for two reasons. First, passing by value can only be done if you have already defined the type, which we have not (we've only declared it). Second, passing by value creates a copy of the object, which in this case means a completely new vector of completely new Player objects, and the changes will not synchronize back to the old object. See here for a better explanation of references.
Next, you need to extract the definition of payMoney to after the definition of Game. The reason is that while the parameter list of payMoney no longer relies on the definition of Game, the code in the function body does (because it calls functions on the engine object). See the end for what this looks like.
This fixes all the problems with declaration/definition order. You also should make payMoney return void as its return value is never provided and never used, pick a consistent type for IDs (either int or unsigned int, not a mix), and add the getPlayerAmount to Game.
Here's what the final code could look like:
namespace Monopoly {
typedef enum { normal, train, company, incometax, luxurytax, start, chancecard, chestcard, jail } type;
class Game;
class Player {
private:
int playerID;
int money;
std::vector<int> propertiesOwned;
void addProperty(int id) {
this->propertiesOwned.push_back(id);
}
public:
// Constructor
Player(int pID, int sMoney) {
this->playerID = pID;
this->money = sMoney;
}
// Functions
void payMoney(int payAmount, int destinationID, Game &engine);
void buyProperty(int id, int price, Game &engine) {
payMoney(price, 0, engine);
addProperty(id);
}
void giveMoney(int payMoney) {
this->money += payMoney;
}
// Returns
inline int getMoney() { return this->money; }
inline int getID() { return this->playerID; }
inline auto getProperties(int index) {
auto p = propertiesOwned[index];
return p;
}
inline int getPropertyAmount() {
int amount = std::size(propertiesOwned);
return amount;
}
};
class Game {
private:
bool running = false;
int turn = 1;
int currentPlayerID;
int startingMoney = 1000;
std::vector<Player> players;
public:
// Functions
void createPlayer() {
++currentPlayerID;
Player newPlayer(currentPlayerID, startingMoney);
players.push_back(newPlayer);
++currentPlayerID;
}
void createPlayers(int playerAmount) {
for (int i = 0; i <= playerAmount; ++i) {
createPlayer();
}
}
Player getPlayer(int index) {
Player p = players[index];
return p;
}
int getPlayerAmount() {
int amount = players.size();
return amount;
}
};
void Player::payMoney(int payAmount, int destinationID, Game &engine) {
this->money -= payAmount;
if (destinationID > 0) {
// Checks if you're paying to a player or bank
bool playerFound = false;
for (int i = 0; i <= engine.getPlayerAmount(); ++i) {
if (engine.getPlayer(i).getID() == destinationID) {
playerFound = true;
break;
}
}
if (playerFound) {
// Player was found
engine.getPlayer(destinationID).giveMoney(payAmount);
return;
}
else {
std::cout << "\nERROR: Invalid player ID at function payMoney\n";
return;
}
}
else {
// You're paying to the bank
}
return;
}
}
Side note: it's technically better C++ to use size_t instead of int for variables storing the size of vectors, as that is what the size functions return (and it's an unsigned integer type whereas int is signed), but that's not especially important.

Virtual function don't work

This code isn't compiled. All problems in virtual function attack() in basic class.
It hasn't got acces to massive in class Team. I was trying do theese classes friend.But it do not work whatever. Also I've done function ptr but it don't work.
Virtual function don't work in inherited classes too. Visual studio 2015 shows errors:
C2228, C2227, C2027.
Please help.
class Team;
class Unit
{
protected:
int hp;
int dmg;
int doodge;
public:
Unit(int hp, int dmg, int doodge): hp(hp), dmg(dmg), doodge(doodge){}
int GetHP()
{
return hp;
}
void SetHP(int hp)
{
this->hp = hp;
}
virtual void attack(Team &T)
{
int id = rand() % 3;
for (int i = 0; i < 3; i++)
if (typeid(*this) == typeid(T.arr[i]))
{
id = i;
break;
}
if (T.arr[id] <= 0)
return;
else
T.arr[id]->SetHP(T.arr[id]->GetHP() - this->dmg);
}
};
class Swordsman:public Unit
{
public:
Swordsman():Unit(15,5,60){}
//virtual void attack(Team & T)override
//{
// int id = rand() % 3;
// for (int i = 0; i < 3; i++)
// if (typeid(Swordsman) == typeid())
// {
// id = i;
// break;
// }
// if (*T.arr[id]->GetHP <= 0)
// return;
// else
// *T.arr[id]->SetHP(T.arr[id]->GetHP() - dmg);
//}
};
class Archer :public Unit
{
public:
Archer() :Unit(12, 4, 40) {}
//virtual void attack(Team & T)override
//{
// int id = rand() % 3;
// for (int i = 0; i < 3; i++)
// if (typeid(Archer) == typeid())
// {
// id = i;
// break;
// }
// if (*T.arr[id]->GetHP <= 0)
// return;
// else
// *T.arr[id]->SetHP(T.arr[id]->GetHP() - dmg);
//}
};
class Mage :public Unit
{
public:
Mage() :Unit(8, 10, 30) {}
/*virtual void attack(Team & T)override
{
int id = rand() % 3;
for (int i = 0; i < 3; i++)
if (typeid(*this) == typeid())
{
id = i;
break;
}*/
};
class Team
{
static short counter;
string name;
Unit* arr[3];
public:
Team()
{
name = "Team " + counter++;
for (int i = 0; i < 3; i++)
{
int selecter = rand() % 3;
switch (selecter)
{
case 0:
arr[i] = new Swordsman();
break;
case 1:
arr[i] = new Archer();
break;
case 2:
arr[i] = new Mage();
break;
}
}
}
~Team()
{
delete[]arr;
}
Unit * ptr(int id)
{
return arr[id];
}
bool check()
{
bool res = false;
for (int i = 0; i < 3; i++)
if (arr[i]->GetHP() > 0)
res = true;
return res;
}
void print()
{
cout << endl << "\t\t" << name << endl << endl;
cout << "\t" << typeid(*arr[0]).name() << endl;
cout << "\t" << typeid(*arr[1]).name() << endl;
cout << "\t" << typeid(*arr[2]).name() << endl;
}
friend class Unit;
};
short Team::counter = 0;
class Game
{
Team A, B;
public:
int Play()
{
while (true)
{
A.ptr(1)->attack(B);
if (A.check())
return 1;
else if (B.check())
return 2;
}
}
};
int main()
{
return 0;
}
Omitting anything irrelevant:
class Team;
class Unit
{
public:
virtual void attack(Team &T)
{
if(typeid(*this) == typeid(T.arr[i]))
// ^^^
{ }
}
};
You are accessing a member of class Team, but at the time given, you only have provided the declaration of Team... Side note: this is not specific to virtual functions, but would occur with any code you write.
Your problem now is that function implementations of both classes Team as well as Unit rely on the complete definition of the other class. So only solution to the problem is to implement one of the functions outside the class, e. g.:
class Team;
class Unit
{
public:
// requires Team, so only declared, not implemented!
virtual void attack(Team &T);
// ^
};
class Team
{
// complete definition!
};
void Unit::attack(Team& t)
{
// now implementation of...
}
Another minor problem is that arr member is private. Well, you provided a getter already (ptr), so use it (and give it a better name...).
If you want to go further towards a clean design, split your units and the team into different compilation units, each coming with a header and a source file:
unit.h:
class Team;
class Unit
{
// private members
public:
// only declarations as above, including constructor/destructor
// by the way: you are lacking a virtual destructor!!!
virtual ~Unit();
};
unit.cpp:
#include "unit.h"
#include "team.h" // fetch the definition of Team!
Unit(/*...*/) { }
Unit::~Unit() { }
// function definitions as shown above...
You would do the same for Team and even your Unit derived classes as well as the Game class. Be aware, though, that you need the complete class definition available if you want to inherit, so you need to include unit.h already int the headers:
archer.h:
#include "unit.h"
class Archer : public Unit
{
// again, only function declarations...
// as base class has already a virtual destructor, own destructor
// gets virtual implicitly (even the default one), so if you do
// not need it, you do not have to define it...
};
archer.cpp:
#include "archer.h"
// and whatever else needed, solely, unit.h already comes with archer.h
// implementations...

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