0

I have the below program. When I try to execute it, I found that Allrounder didn't get the valid name. Any idea how can I solve it?

#include <iostream>
#include <string>
using namespace std;

class Player
{
    std::string playerName;
public:
    Player(std::string &playerName) :playerName(playerName) { cout << "Player Constructed\n"; }
    void printPlayerName() const
    {
        std::cout<<playerName<<endl;
    }
    Player() = default;
    virtual ~Player() { cout << "Player Destructed\n"; }
};

class Batsman : virtual public Player
{
public:
    Batsman(std::string playerName) : Player(playerName) { cout << "Batsman info added\n"; }
    ~Batsman() { cout << "Batsman Destructed\n"; }
};

class Bowler : virtual public Player
{
public:
    Bowler(std::string playerName) : Player(playerName) { cout << "Bowler info added\n"; }
    ~Bowler() { cout << "Bowler Destructed\n"; }
};

class Allrounder : public Batsman, public Bowler
{
public:
    Allrounder(std::string playerName) :Batsman(playerName), Bowler(playerName) { cout << "Allrounder info added"; }
    ~Allrounder() { cout << "Allrounder Destructed\n"; }
};

int main()
{
    Player *ptr = new Batsman("Sachin Tendulkar");
    ptr->printPlayerName();
    delete ptr;
    cout << endl;
    Player *ptr1 = new Bowler("Anil Kumble");
    ptr1->printPlayerName();
    delete ptr1;
    cout << endl;
    Player * ptr2 = new Allrounder("Ravindra Jadeja");
    ptr2->printPlayerName();
    delete ptr2;
    cout << endl;
}

I ensured calling super class constructor, but in case of multiple inheritance, somehow this doesn't seem to work.

Currently ptr2->printPlayerName() failed to print the name of the Allrounder.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
RandomGuy
  • 91
  • 1
  • 10
  • 1
    virtual base construction requires the resolving class on the bottom of the diamond pattern construct the base class at the top *directly*. I.e. `Player(playerName)` needs to be in the `Allrounder` base construction initialization list. Removing `Player() = default;` should have confirmed that, btw. I can't see a reason to have that, and now you have at least one reason *not to*. – WhozCraig Mar 04 '21 at 01:30
  • yeah, worked for me, Thank you – RandomGuy Mar 05 '21 at 00:25

0 Answers0