Reputation: 51
Case: A base class (A) with a function (doSomething) that has a default parameter (param: T = foo), and a subclass (B) which overrides that function with a different default parameter (param: T = bar). But is then called as A.
Edit: Apologies for the original code, so actually what is happening is basically the following:
class Foo
{
func doSomething(a: String = "123")
{
print(a)
}
}
class Bar: Foo
{
override func doSomething(a: String = "abc")
{
print("Using Bar method body... but not Bar's default a value!")
print(a)
}
}
(Bar() as Foo).doSomething()
// Prints:
// Using Bar method body... but not Bar's default a value!
// 123
Is it a bug or expected behaviour that it uses the functions body but doesn't use the functions default parameter?
Upvotes: 5
Views: 1639
Reputation: 6024
It's being called as Foo (or A) because you tell it to. Because you're instantiating Bar() as Foo
, it is doing exactly that.
If you do:
Bar().doSomething()
Bar's method is what is called:
Using Bar method body...
abc
Interestingly, as you point out:
(Bar() as Foo).doSomething()
Yields:
Using Bar method body...
123
Because Bar is instantiated as Foo, (note emphasis) Bar gets Foo's default parameters, yet still executes Bar's function body.
Interesting observation!
Upvotes: 2