Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must unused virtual functions be defined?

I find it quite odd that unused virtual functions must still be defined unlike unused ordinary functions. I understand somewhat about the implicit vtables and vpointers which are created when a class object is created - this somewhat answers the question (that the function must be defined so that the pointers to the virtual function can be defined) but this pushes my query back further still.

Why would a vtable entry need to be created for a function if there's absolutely no chance that virtual function will be called at all?

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

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

Even though I declared A::test() it was never used in the program but it still throws up an error. Can the compiler not run through the program and realise test() was never called - and thus not require a vtable entry for it? Or is that an unreasonable thing to expect of the compiler?

like image 763
AntiElephant Avatar asked Oct 09 '15 20:10

AntiElephant


1 Answers

Because it would inevitably be a very difficult problem to solve on the compiler writer's part, when the usefulness of being able to leave virtual functions undefined is at best dubious. Compiler authors surely have better problems to solve.

Besides, you ARE using that function even though you don't call it. You are taking its address.

like image 57
Edward Strange Avatar answered Sep 21 '22 14:09

Edward Strange