Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading