1

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(); }; 
2
  • Depending on your implementation of FitnessSort can't provide a cast to Citizen in the SCitizen class? Commented Mar 26, 2012 at 14:37
  • FitnessSort just calls MergeSort with sCitizens (causing my problem). The MergeSort would then sort this list based on the fitness variable in the Citizen base class; but i need the associated variable from the SCitizen too.. Commented Mar 26, 2012 at 15:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response; I've rewriten MergeSort like this: MergeSort(std::vector<Citizen*>* list) and void FitnessSort(); sends sCitizens (which is now std::vector<SCitizen*>) but i'm receiving this error: cannot convert parameter 1 from 'std::vector<_Ty> *' to 'std::vector<_Ty> *' with SCitizen * and Citizen *

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.