mercredi 31 mai 2017

How to avoid possible object slicing when storing derived classes in a vector

I have a base class called Platform. It has some derived classes like Game, Book, Series, etc. I'm currently making a database like program, and I want to store all my objects in a vector, each row of that vector creates another vector, and that vector will be associated with a single platform. Since i want this to be more dynamic when I add more platforms and such. The issue is that I believe i have object slicing when I go and do this.

my Platform base class has a virtual getName() and setName() method with a protected string variable called name.

My derived Book class of course recreates the getName() and setName() methods without virtual and to suit the class's criteria. I also added getPage() and setPage() methods to represent the number of Pages inside of the book.

vector<*Platform> platforms
vector<vector<Platform*>> database;
Book tmpBook;
tmpBook.setName("ANYNAME");
tmpBook.setPage(376);
platforms.push_back(&tmpBook);
database.push_back(platforms);
cout << database[0][0]->getName() << database[0][0]->getPage() << endl;

expecting output of ANYNAME 376, but apparently theres an issue with the getPage command, my first fear was that object slicing has occurred. ERROR: CLASS PLATFORM HAS NO MEMBER NAMED 'getPage' So please tell me has object slicing occurred here, or am i missing something crucial but simple?

What is the solution to my problem, will I have to use unique pointers or shared pointers or boost or something? If so how would I model that?

Aucun commentaire:

Enregistrer un commentaire