Why should unused virtual functions be defined?

I find it rather strange that unused virtual functions should be defined as opposed to unused regular functions. I am a little versed in the implicit vtables and vpointers that are created when the class object is created - this somewhat answers the question (what function should be defined so that pointers to a virtual function can be defined), but this still returns my request.

Why does a function need to create a vtable entry if there is no chance that the virtual function will be called at all?

class A{
    virtual bool test() const;
};

int main(){
    A a; //error: undefined reference to 'vtable for A'
}

Despite the fact that I announced A::test(), it was never used in the program, but it still throws an error. Can the compiler not run through the program and test()never be called - and, therefore, does not require a vtable entry? Or is it unreasonable to expect from the compiler?

+4
source share
3 answers

Because it will inevitably be a very difficult task to solve the compiler part, when the utility of the ability to leave virtual functions undefined is at best doubtful. The compiler authors certainly have problems to solve.

In addition, you use this function even if you do not name it. You take his address.

+5

OP , vtables vpointers, , : , , vtable . , , , , vtable, . undefined.

.cpp , , - , .

, "" - . . , .

, , undefined, , -: , , , , . , . , undefined, : .

, , ASSERT(FALSE) .

+3

, . , ? , ( ), , , , . , .

0

Source: https://habr.com/ru/post/1611019/


All Articles