I have a superclass Entry
and subclasses MusicAlbum
, Book
and Film
. Instances of these subclasses are stored according to the name of the item ie Book1
. The name and type of all these instances are stored in a vector cat_vector
which is a vector of objects of class libCatalogue
which simply stores the name and type:
class libCatalogue{
std::string name;
std::string type;
public:
libCatalogue(std::string name, std::string type);
std::string getname();
std::string gettype();
};
libCatalogue::libCatalogue(std::string name, std::string type) :name(name), type(type) {};
std::vector <libCatalogue> cat_vector;
Entries in the vector are made in the constructor eg.
MusicAlbum::MusicAlbum(std::string a, std::string b, std::string borrower)
: name(a), artist(b), Entry(borrower){
cat_vector.push_back(libCatalogue(name, "MusicAlbum"));
Each subclass has a member function called printdetails()
. I want to use a loop to step through each entry in cat_vector
and print the details of the entry but the following does not work:
int no = 1;
for (auto it = begin(cat_vector); it != end(cat_vector); ++it)
{
std::string name_ = it->getname();
std::string type_ = it->gettype();
std::cout << "Entry no. " << no << std::endl;
std::cout << "Name: " << name_ << std::endl;
std::cout << "Type: " << type_ << std::endl << std::endl;
if (type_ == "MusicAlbum"){
name_.printdetails(); //print using MusicAlbum member function
}
//etc...
no++;
I know it is because name_
is a string and not an object of any of the classes I want to call, but I haven't been able to find any way to convert it so far. Is there any way to tell the compiler that name_
is referring to an object of one of the subclasses?