On 10 April 2013 20:29, Regan Heath <re...@netmail.co.nz> wrote: > Ok, lets Rewind for a sec. I need some educating on the actual issue and > I want to go through the problem one case at a time.. > > > #1 If I write a class.. > > class A > { > public int isVirt() { return 1; } > public int notVirt() { return 2; } > } > > and compile it with another class.. > > class B : A > { > override public int isVirt() { return 5; } > } > > and this main.. > > void main() > { > A a = new B(); > a.isVirt(); // compiler makes a virtual call > a.notVirt(); // but not here > } > > Right? > > > #2 But, if I do /not/ compile class B and have.. > > void main() > { > A a = new A(); > a.isVirt(); // not a virtual call > a.notVirt(); // neither is this > } > > Right? > > > #3 If I put class A into a library (lib/dll) then compile/link it with.. > > class B : A > { > override public int isVirt() { return 5; } > } > > and.. > > void main() > { > A a = new B(); > a.isVirt(); // compiler makes a virtual call > a.notVirt(); // we're saying it has to make a virtual call here too > } > > So, when the compiler produced the library it compiled all methods of A as > virtual because it could not know if they were to be overridden in > consumers of the library. > > So, if the library created an A and passed it to you, all method calls > would have to be virtual. > > And, in your own code, if you derive B from A, then calls to A base class > methods will be virtual. > > Right? > > R >
All your examples all hinge on the one case where the optimisation may possibly be valid, a is _allocated in the same scope_. Consider: void func(A* a) { a.isVirt(); // is it? I guess... a.notVirt(); // what about this? } We don't even know what a B is, or whether it even exists. All we know is that A's methods are virtual by default, and they could be overridden somewhere else. It's not possible to assume otherwise.