UML Diagram : https://i.stack.imgur.com/ajsVQ.png
My OOP teacher said that we could implement something like in the above diagram in C++ (for a lab assignment). She said we could do something like this so we wouldn’t need two List classes (one for Books and one for Clients).
I started implementing it and i’m stuck on getFromPosition(int) (it is supposed to return the object at certain position in the list). What I am trying to do is to save a Book object in a List object (this works fine) and i would later like to be able to return/read/modify these saved Book objects.It returns the object , but then I (probably) should make a cast of some sort so I could use the methods of the Book. Is this even possible?
This is the code for the method:
Obj List::getFromPosition(int i){
return list[i];
}
I hope I gave enough info (this is my first question ).
Thanks in advance!
Since you’re returning an
Objby value, I’m guessing internally you hold a collection ofObjobjects, and not pointers.Which is wrong. You run into object slicing.
Firstly, you should keep pointers or smart pointers internally, and return an
Obj*or aSmartPtr<Obj>.Second, whether you need the cast or not depends.
If you have a common method between your deriving classes, it should probably go in the base class. If not, you probably need a cast.
Here’s how I’d do it rough cut: