I am new to coding and just learnt how to use classes so sorry if I am making a very simple mistake here.
I want The Move() Function here to take speed, damage and health inputs from the subclasses, take xpos and ypos default and xmove, y move and name from Int Main();
#include <iostream>
class Player
{
public:
int xpos = 0; int ypos = 0;
int health, damage, speed;
// Move function takes these above as inputs
void Move(std::string name, int xmove, int ymove)
{
xpos += xmove * speed;
ypos += ymove * speed;
std::cout << name << " moved " << xpos << " spaces" << std::endl;
std::cout << "Health = " << health << std::endl;
std::cout << "Damage = " << damage << std::endl;
}
};
class pTank : public Player
{
public:
//I want these as inputs in move function
int speed = 1;
int health = 200;
int damage = 20;
};
class pSamurai: public Player
{
public:
int speed = 4;
int health = 100;
int damage = 50;
};
int main()
{
pTank player1;
std::string p1 = "Player1";
player1.Move(p1,1,1);
}
It gives the output
Player 1 moved -856…. places
health = -865….
damage = -876….
Which I am assuming is because the values are not declared yet.
>Solution :
This here:
class pTank : public Player
{
public:
//I want these as inputs in move function
int speed = 1;
int health = 200;
int damage = 20;
};
Does not set the member variables of Player. Instead it declares new variables and shadows the old. Hence, Player::speed is never initialised.
Have a constructor for Player:
Player(int speed, int health, int damage) : speed{speed}, health{health}, damage{damage} {}
And then one for pTank:
pTank() : Player(1, 200, 20) {}
You can also aggregate initialise Player instead.