call redefined virtual function in parent constructor

Hi, I have following problem : I had implemented an algorithm, that uses in its constructor a virtual function , for example run. I create another version of algorithm via public inheritance -child of the previous and redefined 'run' function. When instance of new algorithm is created, constructor of parent is invoked, but it uses parent's run. Why ? It is bad design ? Thanks for any advice.

class algorithm1 {
public:
algorithm1(int i){run();}
virtual void run(){//do something};
}


class algorithm2: public algorithm1 {
public:
algorithm2(int i):algorithm1(i){}; // run of parent is called
virtual void run(){//do something else };
}
Last edited on
derived class contructor (always) calls the base class constructor (before the derived class constructor starts) - if the base class constructor calls a virtual function, then the base class
version is used because the derived class does not yet exist.

Edit:
Note that if the virtual function in the base class is a pure virtual function - then you will
have a problem.
Last edited on
Yes, very bad design. Never call virtual methods in constructors or destructors unless you want these very subtle bugs.
Thank you, i didn't know this fact in c++ . One friend adviced me the nice article about it . http://www.artima.com/cppsource/nevercall.html .

jsmith > I tried to find a way, implement those algorithms as shown, because i wanted use algorithms without explicit calling run() on theirs instances. Probably explicit call is solution, or ovreloaded operator(). Is there some other approach ?
One possibility is to make a factory. The factory would have to call run(), but at least the user wouldn't have to.

Topic archived. No new replies allowed.