Home > other >  C constructor call non-virtual function, let's say funcA, but funcA calls a virtual function,
C constructor call non-virtual function, let's say funcA, but funcA calls a virtual function,

Time:08-09

I know we better don't call a virtual function in the constructor since the derived class construction not started yet based on https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctors , but what's going on if we call a non-virtual function in constructor, but the non-virtual function call a virtual one, is it dangerous as well?

If YES, then how can we avoid it, if the call stack for a non-virtual is more deep, we cannot be aware of this issue, right?

class A
{
    public:
    A()
    {
        funcA();
    }
    void funcA()
    {
        func1();
    }
    virtual void func1(){
        std::cout << "A func1" <<std::endl;
    }

};

class B : public A
{
    public:
    B()
    {

    }

    virtual void func1(){
        std::cout << "B func1" <<std::endl;
    }

};

CodePudding user response:

if we call a non-virtual function in constructor, but the non-virtual function call a virtual one, is it dangerous as well?

Yes. Take this example:

struct foo {
    foo() { proxy(); }
    void proxy() { call(); }
    virtual void call() = 0;
};

struct bar : foo {
    void call() override {}
};

Instantiating bar will most likely result in a runtime fault. It may print something like "pure virtual method called" and die.

how can we avoid it, if the call stack for a non-virtual is more deep, we cannot be aware of this issue, right?

Not without analysing the code. You may find a static analyzer that is capable of catching this - or you'll have to do it manually.

  •  Tags:  
  • c
  • Related