I have the following setup:
main.cpp:
int main() { vector <Tour> tourList; Tour* tour_ptr; for (unsigned int i = 0; i < tourList.size(); i++) { tour_ptr = &tourList[i]; tour_ptr->display(); } } Tour.h:
class Tour { public: virtual void display(); }; Tour.cpp:
void Tour::display() { cout << "Tour ID: " << getID() << "\n"; cout << "Description: " << getdescription() << "\n"; cout << "Tour Fee: $" << getfee() << "\n"; cout << "Total Bookings: " << getbookings() << "\n\n"; } GuidedTour.h:
class GuidedTour : public Tour { public: void display(); }; GuidedTour.cpp:
void GuidedTour::display() { Tour::display(); cout << "Max Tour Group Size: " << getMaxTourists() << "\n"; cout << "Tour Guide: " << getGuideName() << "\n"; cout << "Tour Date: " << getTourDate() << "\n\n"; } GuidedTour inherits from the Tour class, and I've specified the display() function as virtual in the base Tour class, but for some reason, the GuidedTour display() function never gets called, only the base function gets called every time. What am I doing wrong?
vector<Tour>holdsTourobjects. It can NOT holdGuidedTourobjects so if you push one into the vector it slices off the Tour part and puts it in the vector. If you want to hold polymorphic objects in a vector you need to use pointersstd::vector<Tour*>or preferablyboost::ptr_vector<Tour>