Jimmy Jag Jimmy Jag - 1 month ago 19
C++ Question

C++ inheritance and Vitual Functions

I've tried to create two simple classes that demonstrate the issue that I keep having. It seems to me that I am getting an error just trying to make use of a virtual function. I feel like there I'm missing something basic.

Primary Issue: in my for loop at the end I get an "Expression must have class type" error which seems like it defeats the whole purpose of a virtual function to me.

Secondary Issue: I'd like to sort the list alphabetically by name but I get the same "must have class type" error. The commented version is another method I've tried but it doesn't work as is because name is protected.

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <list>

using namespace std;


class Player
{
public:

Player()
{
position = "Default_P";
name = "Default_N";
}

Player(string pos, string nam)
{
position = pos;
name = nam;
}

virtual void playerPrint()
{
cout << "Player Name: " << getNam() << " position: " << getPos() << endl;
}

string getPos() { return position; }
string getNam() { return name; }


protected:
string position;
string name;

};


class Goalie : public Player

{

public:
Goalie(string pos, string nam, int sav)
{
saves = sav;
}

int getSav() { return saves; }

virtual void playerPrint()
{
cout << "Goalie Name: " << getNam() << " Saves: " << getSav()
<< endl;
}

protected:
int saves;

};


int main()

{
list<Player*> PlayerList;

PlayerList.push_front(new Player("Offense", "Alex"));
PlayerList.push_front(new Player("Offense", "Carl"));
PlayerList.push_front(new Player("Defense", "Eddy"));
PlayerList.push_front(new Goalie("Goalie", "Aaron", 22));
PlayerList.push_front(new Goalie("Goalie", "Drew", 20));

//PlayerList.sort([](Player* a, Player* b) {return a->name < b->name;});

PlayerList.sort([](Player* a, Player* b) {return a.getNam() < b.getNam();});
//Error: Expression must have class type for a and b

for (Player* p1 : PlayerList)
{
p1.playerstring(); //Error: Expression must have class type for p1
}

return 0;

}


please forgive me for any formatting issues. I hope it's still readable
and yes I understand it's a redundant to have a goalie object with position = "Goalie" but it's just a demonstration.

Answer

In the problematic code:

for (Player* p1 : PlayerList)
{
    p1.playerstring();  //Error: Expression must have class type for p1
}

, the type of p1 is Player *, which is not at all the same thing as Player. The former is a pointer type, not a class. Inside the loop, you should use the form

p1->playerstring();

or the equivalent, more illustrative form

(*p1).playerstring();

to invoke a method on the pointed-to object.

The same applies to the comparison method with which you are trying to sort.

Comments