banarun
banarun

Reputation: 2321

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.

Upvotes: 2

Views: 123

Answers (3)

Balog Pal
Balog Pal

Reputation: 17163

Are you sure what you write is true? What is your proof in optimized build?

My observations are that if the program does contain code to create a single instance of A, then VMT is not linked with the program and the functions, including virtuals are not used either.

Upvotes: 0

Steven M. Wurster
Steven M. Wurster

Reputation: 360

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.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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).

Upvotes: 8

Related Questions