TourManager.h

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <typeinfo>
#include "Tour.h"
#include "GuidedTour.h"

using namespace std;
class TourManager {

private:
    vector<Tour *> list;
    void setupTour();
    void callDisplayOnEach();

public:
    TourManager();
    void go();
};

TourManager.cpp

#include "TourManager.h"

TourManager::TourManager() {

    setupTour();
}

void TourManager::setupTour() {

    list.push_back(new Tour("BG002", "Botanical Gardens Entry Pass", 30.00));
    list.push_back(new GuidedTour("SK003", "Learn to Ski Adventure Tour", 240.00, "28/07/2008", "Zail S", 25));
}

void TourManager::callDisplayOnEach() {

    for(vector<Tour *>::iterator it = list.begin() ; it != list.end(); ++it) {

        (*(*it)).display();
    }
}

Guided tour is a sub class of the Tour. It overrides display method of the parent tour class. However when I loop through tour objects vector and call display, it always call the tour::display even if the object is a GuidedTour.

What am I doing wrong here?

I'm using C++98 Many thanks.

有帮助吗?

解决方案 2

finally figured it out.

In the tour class

virtual void display():

so it can be overridden in the subclass :D

其他提示

Both of your display methods must be virtual for this to work.


Also, consider using an std::unique_ptr. Raw pointers should never own memory. It's also good for you because when the vector goes out of scope, the destructors of the unique pointers will clear the allocated memory for you.

Nevermind, C++98 only has std::auto_ptr. The Boost libraries have their own smart pointers however. Look into boost::scoped_ptr.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top