I want the int Medals which I put private to be unable to have negative values, but I don't know how to implement that encapsulation along with constructors. I made it so that each athlete type inherits the Athlete constructor but I don't know where to call the setMedals function for it to work.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class Athlete {
private:
int Medals;
public:
string Name;
void setMedals(int newMedals) {
if (newMedals >= 0)
Medals = newMedals;
}
int getMedals() const{
return Medals;
}
virtual string getDescription() = 0;
Athlete(string _Name, int _Medals) : Name(_Name), Medals(_Medals) {}
};
class Footballer : public Athlete {
public:
string getDescription() {
return "Footballer ";
}
Footballer(string Name, int Medals) : Athlete(Name, Medals) {}
};
class Basketballer : public Athlete {
public:
string getDescription() {
return "Basketballer ";
}
Basketballer(string Name, int Medals) : Athlete(Name, Medals) {}
};
ostream& operator <<(ostream& output, vector<Athlete*> athletes) {
for (int i = 0; i < athletes.size(); i++) {
output << athletes[i]->getDescription() << " " << athletes[i]->Name << ": " << athletes[i]->getMedals() << " Medals" << endl;
}
return output;
}
void printAthletes(vector<Athlete*> athletes) {
sort(athletes.begin(), athletes.end(), [](Athlete* a, Athlete* b) {
return a->getMedals() > b->getMedals(); });
cout << athletes;
}
int main() {
Footballer Andrew("Andrew", 3), Jack("Jack", 4);
Basketballer David("David", 5), Rob("Rob", 1);
vector<Athlete*> Athlete = { &Andrew, &Jack, &David, &Rob };
printAthletes(Athlete);
return 0;
}
I hope you understand my question cause I don't know how else to phrase it.