Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I take input from the the sub class here? When I run this code it uses the values from superclass in Move() Function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading