Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't compiler make a virtual function non virtual when it is possible?

class A{
     void virtual a(){}
};
int main() { 
    std::cout<<sizeof(A);
}

In the above case why doesn't the compiler make the function non virtual and save the space allocated to it. Is there a specific reason for not doing that?

I am using gcc 4.7 compiler, if it is compiler specific.

like image 350
banarun Avatar asked Apr 16 '26 09:04

banarun


2 Answers

Because you may create a derived class in a separate translation module.

In theory this could be resolved at link time, but this would involve a lot of work, so in practice that doesn't happen (AFAIK).

like image 63
Oliver Charlesworth Avatar answered Apr 17 '26 23:04

Oliver Charlesworth


The compiler proper probably won't do this because it doesn't know what's in other files.

The linker might be able to do this, but there is no guarantee that a descendant version of A doesn't exist somewhere and will be loaded in a separate module.

like image 42
Steven M. Wurster Avatar answered Apr 17 '26 23:04

Steven M. Wurster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!