inheritance - Different behaviour of method overloading in C# -
inheritance - Different behaviour of method overloading in C# -
going through c# brainteasers (http://www.yoda.arachsys.com/csharp/teasers.html) , came across 1 question: should output of code?
class base of operations { public virtual void foo(int x) { console.writeline ("base.foo(int)"); } } class derived : base of operations { public override void foo(int x) { console.writeline ("derived.foo(int)"); } public void foo(object o) { console.writeline ("derived.foo(object)"); } } class test { static void main() { derived d = new derived(); int = 10; d.foo(i); // prints ("derived.foo(object)" } }
but if alter code
class derived { public void foo(int x) { console.writeline("derived.foo(int)"); } public void foo(object o) { console.writeline("derived.foo(object)"); } } class programme { static void main(string[] args) { derived d = new derived(); int = 10; d.foo(i); // prints derived.foo(int)"); console.readkey(); } }
i want why output getting changed when inheriting vs not inheriting; why method overloading behaving differently in these 2 cases?
as specified in answers page:
derived.foo(object) printed - when choosing overload, if there compatible methods declared in derived class, signatures declared in base of operations class ignored - if they're overridden in same derived class!
in other words, compiler looks @ methods freshly-declared in derived class (based on compile-time type of expression) , sees if applicable. if are, uses "best" 1 available. if none applicable, tries base of operations class, , on. overridden method doesn't count beingness declared in derived class.
see sections 7.4.3 , 7.5.5.1 of c# 3 spec more details.
now why it's specified - don't know. makes sense me methods declared in derived class take precedence on declared in base of operations class, otherwise run "brittle base of operations class" problem - adding method in base of operations class alter meaning of code using derived class. however, if derived class overriding method declared in base of operations class, it's aware of it, element of brittleness doesn't apply.
c# inheritance method-overloading
Comments
Post a Comment