user1293210
user1293210

Reputation: 11

C++ Class function inheritance using variable of another class that is inherited from base class

The MergeSort runs through the vector given it and sorts via the fitness variable in my Citizen base class.

I want to use this in my SGA class to do the same with its SCitizen (which inherits the fitness variable?); but I'm unable to as the function requests a Citizen type.

Is it not possible to use the derived class for the same function, as the function only uses members of the base class that all classes will have? Or have I missed something in the setup of the classes?

Thanks for any help! Sorry if this is repeat; I had a search on here and a google but came up with nothing - I wasn't even particularly sure what to google..

class Citizen
{
public:
       double fitness;

       Citizen();
};

class SCitizen : public Citizen
{
public:
       std::string code;

       SCitizen();
};

class GA
{
public:
       std::vector<Citizen>* citizens;
       void MergeSort(std::vector<Citizen>* list);
};

class SGA : public GA
{
public:
       std::vector<SCitizen>* sCitizens;
       void FitnessSort();
};

Upvotes: 1

Views: 159

Answers (1)

JaredPar
JaredPar

Reputation: 754525

In order for the vector<T> to store Citizen values and all of it's sub-types you need to use a vector<Citizen*>. A vector<Citizen> can only store Citizen values and will slice off any sub-types which are used.

Upvotes: 1

Related Questions