Can the fragile base class problem occur in C++?

Viewed 179

I stumbled across the Fragile Base Class Wikipedia article.

I understand the infinite cycle caused by the last example. But to my understanding, it can not occur in C++, as in C++ the compiler would compile inc1() once for all into binary code with hard coded jump to Super's inc2 (instead of Sub's inc2). Is this correct?

2 Answers

Konrad Rudolph shows that C++ has this exact same problem. I want to present here some solutions

A solution mentioned in the wiki is to make inc2 final.

However, depending on your situation, a better solution could be to explicitly call the base method from Base:

class Base {
    int counter = 0;

public:
    virtual void inc1() { Base::inc2(); } // <-- now safe
    virtual void inc2() { ++counter; }
};

class Derived : public Base {
public:
    void inc2() override { inc1(); }
};

The example in the article is directly translatable to C++, and exhibits the same issue:

class Super {
    int counter = 0;

public:
    // First version:
    // virtual void inc1() { ++counter; }
    // Changed to:
    virtual void inc1() { inc2(); }
    virtual void inc2() { ++counter; }
};

class Sub : public Super {
public:
    void inc2() override { inc1(); }
};
Related