简体   繁体   中英

vectors containing pointers to polymorphic classes

I have some troubles understanding how to correctly use vectors of pointers in relation with polymorphic classes. Suppose I have a polymorphic structure:

Parent class

class Bumper {

    protected:
    double mu_;

    public:
    Bumper(){};
    Bumper(double mu):mu_(fabs(mu)){};

    void Set_mu(double mu){mu_=mu;};
    virtual void Bounce (Ball & myB)const{myB.change_speed(-sqrt(mu_));};

};

Child class

class ThresholdBumper : public Bumper {

    protected:
    double eps_;

    public:
    ThresholdBumper(double eps):Bumper(1.5), eps_(eps){};

    virtual void Bounce (Ball & myB){
            if(myB.energy()<eps_){Set_mu(1); Bumper::Bounce(myB); Set_mu(1.5); return;};
            Bumper::Bounce(myB);
    };


};

Function

void flipper (Ball & myB, vector<Bumper*> & Obst){
    for(int i=Obst.size()-1; i>=0; i--){
            Obst[i]->Bounce(myB);
    };
};

change_speed() is a void function changing private parameters inside the class Ball, and energy() is a scalar function. This code:

 vector<Bumper*> myBumpers1(10);

 for(int i=0; i<10; i++){
       myBumpers1[i]=new ThresholdBumper(drand48()*5);
 };

 flipper(myBalls2,myBumpers1);

does not work, since Bumper::Bounce() gets called in the "flipper" function. Which means that the function seems to not recognize that there is polymorphism. Can someone explain me why? In particular, redifining the function as:

Function'

 void flipper(Ball & myB, vector<Bumper*>::iterator begin, vector<Bumper*>::iterator end){
    vector<Bumper*>::iterator it;
    for(it=end-1; it!=begin; --it){
            (*it)->Bounce(myB);
    };
};

makes everything work well, as expected. What is the difference exactly?

Your child class actually declares separate Bounce function instead of overriding base class Bounce . Notice that in base class it is declared as const . You should redeclare it in child class as

void Bounce (Ball & myB) const override {

override keyword ensures that a virtual function of base class is being overriden

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM