vendredi 30 juin 2017

Reset a derived class object

I'd like to achieve something like this below:

class A {
public:
    virtual void reset() {
    // 1). if there's no override to this function,
    // then whatever derived from A should get reset
    // to its constructed state, e.g. if B derives from
    // A, then *this = B();
    // 2). if there is an override to reset in the derived 
    // class, call the reset in the derived class
    }
};
class B: public A {
public:
    B() { std::cout<<"reset B"<<std::endl; }
    // no override of reset() here
}; 
class C: public A {
public:
    void reset() override {
        std::cout<<"reset C"<<std::endl;
    }
};

N.B. A doesn't know which class will derive from it, but whoever derive from it, if there is no reset() override in that derived class, calling A::reset() should reset the derived class object to its constructed state, i.e.

A* a = new B();
a->reset(); // -> this equals to *a = B();

However, if there is an override of reset() in the derived class, calling A::reset() should call the overridden reset(), i.e.

A* a = new C();
a->reset(); // -> this should call C::reset()

Aucun commentaire:

Enregistrer un commentaire