Must the entire class hierarchy be recompiled if a virtual or non-virtual function is added to the base class in C++?

前端 未结 2 359
北荒
北荒 2021-01-22 00:11

I am trying to learn how sensitive the vtable of a class is in C++ and, for that, I need to know whether recompilation of the entire class hierarchy (total, 3 header files) is n

相关标签:
2条回答
  • 2021-01-22 00:50

    The C++ one-definition-rule makes it clear that definitions of entities in different translation units (ie: files) must all be identical if you're going to link them together. As such, if you change the definition of a class at all, public, private, virtual, non-virtual, whatever, all translation units that use that definition have to be looking at the new class definition. And that will require recompiling it.

    Failure to do this is il-formed, but no diagnostic (linker-error) is required. So your project may appear to link just fine. Indeed, it may actually work in some cases. But there's nothing which guarantees in which cases they will work and in which cases they will not.

    0 讨论(0)
  • 2021-01-22 00:54

    Regardless the missing virtualdestructor of A you have an interface here:

    class A {
       public:
       virtual void method1() = 0;
       virtual void method2() = 0;
       virtual ~A() {} // This is needed
    };
    

    An interface is a contract that shouldn't be broken.

    If you want to extend interfaces without the need to recompile the complete codebase, you can use inheritance and dynamic polymorphism checks:

    class AEx : public A {
    public:
       virtual void method3() = 0;
       virtual ~AEx() {}
    }; 
    

    In functions which handle the extensions you can do

    void foo(A* pA) {
        AEx pAEx = dynamic_cast<AEx*>(pa);
        if(pAEx) {
           pAEx->method3();
        }
    }
    
    0 讨论(0)
提交回复
热议问题