Why does my compiler insist on unused function definitions only for virtual?

41 views Asked by At

You can have however many functions you like declared in a class and the only warning I get is a little green squiggle when it's not used and not defined. I understand this.

What I don't understand is if I make the unused function virtual, then I have to define the function, even if I don't call it. However this is only if I instantiate the class. So in the following:

struct Animal
{
    void unusedFunc();          // <--- Regardless of whether class is instantiated, this does not need to be defined unless it is called
    virtual void unusedVirtualFunc(); // <--- Has to be defined whether or not it is called, but only if this class is instantiated.
};

int main()
{
    Animal dog1;          // <--- This line now means the virtual function has to be defined. Doesn't affect the non-virtual function at all.
}

As soon as I add the virtual keyword my class grows to 8 bytes (the vtable pointer). Travelling to wherever the vtable pointer points I imagine I'd arrive at the vtable which has the instructions needed to execute the function particular to the object, identified at runtime, but I can't see the need for this function definition to be in the vtable at all. Sorry if this is an obvious question.

Also, I'm on Visual Studio.

Edit: Here is some compilable code:

struct Animal
{
    void unusedFunc();
    virtual void unusedVirtualFunc();
};


int main()
{
    Animal dog1;
}
0

There are 0 answers