Home > Back-end >  no viable overloaded '=' and inheritance
no viable overloaded '=' and inheritance

Time:09-17

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.

CodePudding user response:

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();
  • Related