I'm currently in the middle of a project for school in which I have to "translate" a Java program into C++.
The program emulates a media library and uses inheritance. Basically, you have a media library which you can add items to. The different kinds of items you can add are Books, Movies, and MusicAlbums.
I have a class Library, which main creates an instance of, and which has a container to hold all of my items. Item is the superclass, and Book, Movie, and MusicAlbum are its derived classes.
Here's where I'm having problems translating from Java to C++:
My instructor provided "Main.cpp", and I have to write the rest of the program based off of that. I am not allowed to modify it or the assignment is invalid. However, "Main.cpp" calls
cout << item << endl;
every time that it adds an item to the media library. So, that of course sends it to Item.cpp , where I've overridden the << operator.
Now, I have to be able to figure out whether that "item" is a Book, Movie, or MusicAlbum before I write the code for outputting its data, because each one of those things needs to be printed differently.
In my Java program, I wrote something like:
if(item instanceof Book){
System.out.println((Book) item); // I overrode "toString" in Book.Java
}
elseif(item instanceof Movie){
System.out.println((Movie) item); // overwrode "toString" in Movie.java
}
else
{
System.out.println((MusicAlbum) item; // overrode "toString" in MusicAlbum.java
As you can see, I used instanceof to determine which type of item it was, and then I cast the item to that derived type before passing it to println, after overriding all of the derived class's "toString" methods.
I don't know how to do this in C++. I've looked at tons of similar questions on stackoverflow and other forums, and they all either suggest things that I tried and didn't work, or they tell you how to cast the item to the derived type but not how to just -check- which derived type it is without actually changing it first.
If anyone has any insight into how this would work in C++ I would be very grateful. Thank you.