简体   繁体   中英

C++ constructor call non-virtual function, let's say funcA, but funcA calls a virtual function, is it dangerous

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;
    }

};

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.

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