2

I have the following class structure but when I build, I keep getting the error:

error: no viable overloaded '='
                        p1 = new HumanPlayer();
                        ~~ ^ ~~~~~~~~~~~~~~~~~
../Test.cpp:14:7: note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'HumanPlayer *' to 'const Player' for 1st argument; dereference the argument with *
class Player {
      ^
1 error generated.
class Player {
public:
    void getMove(int player) {
        cout << "Get move" << endl;
    }
};

class HumanPlayer: public Player {
public:
    void getMove(int player) {
        cout << "Get Human move \n";
    }
};

class MyClass {
public:
    int mode;
    Player p1;

    MyClass() {
        mode = 0;
        cout << "Choose a mode: \n";
        cin >> mode;
        switch (mode) {
            case 1:
            p1 = new HumanPlayer();
            break;
            default:
            break;
        }
        p1.getMove(0);
    }
};

int main() {
    MyClass c;
    return 0;
}

I tried to change the Player p1; to Player* p1; and changed p1.getMove to p1->getMove but then it did not work correctly. It printed Get move instead of Get Human move.

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
Amy Cohen
  • 109
  • 12
  • 2
    `new` returns a pointer. In the second case, getMove is not marked `virtual` so it is not polymorphic. – user253751 Sep 08 '21 at 13:10
  • 3
    A constructor should do simple and basic initialization of the object. It should not do advanced things like terminal input and output. Better leave that to other functions. – Some programmer dude Sep 08 '21 at 13:13
  • I suspect that you have been programming in some other languages, where `new` is the way you create objects. C++ is not those languages. Get a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about polymorphism. – molbdnilo Sep 08 '21 at 13:15
  • Yes I've been using Java and quite new to C++ (hence the use of `new`) – Amy Cohen Sep 08 '21 at 13:18

1 Answers1

3

as commented above

p1 = new HumanPlayer();

is valid if p1 is declared as pointer, unlike java you can in c++ assign with and without the new keyword...

in your case declaring p1 as pointer will be ok

Player* p1{nullptr};
 

and later

p1 = new HumanPlayer();
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97