Reputation: 67
I've some trouble with the following task.
At first I had a vector with just one type of objects(bikes).
I could use this objects to put them into a class and used a function to print out the brands and model of those bikes like this:
for (Bike* b1 : vecBikes) {
b1->printBrandModel();
}
My class's name is Bike.
From this class I derived two new classes, which are MTB for Mountain Bikes and E_Bikes. I read the file again and stored them either as MTB or E_Bike objects into my vector like this:
while (inputFile >> brand >> model >> modelyear >> price >> type) {
if (type == "MTB") {
vecBikes.push_back(new MTB(brand, model, modelyear, price));
}
else {
inputFile >> energy;
vecBikes.push_back(new E_Bike(brand, model, modelyear, price, energy));
}
getline(inputFile, buffer);
}
Now I want to do pretty the same. But this time I want to print eihter MTB's or E_Bikes from this vector.
Maybe a dynamic_cast is the way to go but I'm a complete beginner on this subject and all those examples books and websites can't help me somehow. I hope you can help me out on this ;-)
Upvotes: 0
Views: 66
Reputation: 840
You can use dynamic_cast for determining the object type as below:
for (Bike* b1 : vecBikes) {
if(dynamic_cast<MTB*>(b1) != nullptr) {
b1->print_MBT();
} else if (dynamic_cast<E_Bikes*>(b1) != nullptr) {
b1->print_E_Bikes();
} else cout << "error" << endl;
}
Moreover, if you define a pure virtual method printBrandModel
in your base class, you can(must) implement it as desired in derived classes. So you can use the first code without determining the instance belongs to which class.
for (Bike* b1 : vecBikes) {
b1->printBrandModel();
}
Upvotes: 2