Download

Problem when call overrided virtual void from constructer

Hey guys, I’ve met a broblem with derived classes’ constructer and overrided functions:
Heres two classes: A->B

with A.h


class A
{
    virtual void Func();
}


A.cpp


A::A()
{
    Func();
}
void Func()
{
  exprs..
}


with B.h


class B: A
{
   void Func() override;
}

B.cpp


void Func()
{
  different exprs..
}

The result seems always to be execute A’s Func instead of the overrided one of B’s while there is only B in current level.

Is it impossible to do so? I’ve searched out tons of answers for a whole day but the problem’s still there.

I think maybe the best way is to totally rewrite the constructer of B’s?

Any help could be very appreciated!~

Yes, calling virtual functions from a constructor should be avoided.

See for example here:

Yep, I’m now working on another way .Thx!