Polymorphism; simple question

  • Thread starter Thread starter David Vestal
  • Start date Start date
D

David Vestal

Which version of foo() is bar() going to call? I'm not seeing what I
expected to see.

class A{}
class B : A{}
class C
{
public void foo(A a){}
public void foo(B b){}
}

some function bar()
{
C c = new C();
A obj = new B();

c.foo(obj);
}
 
David Vestal said:
Which version of foo() is bar() going to call? I'm not seeing what I
expected to see.

class A{}
class B : A{}
class C
{
public void foo(A a){}
public void foo(B b){}
}

some function bar()
{
C c = new C();
A obj = new B();

c.foo(obj);
}

I'd expect foo(A a) to be called. The method signature is determined at
compile time - and at that stage, the compiler only knows that the obj
is an "A" reference.
 
Just for fun...

using System;

namespace FooFooFoo

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

C c = new C();

A obj = new B();

c.foo(obj);

}

}

public class A {}

public class B : A {}

public class C

{

public void foo(A a)

{

System.Diagnostics.Debug.WriteLine("C:foo(A) Has been called");

}

public void foo(B b)

{

System.Diagnostics.Debug.WriteLine("C:foo(B) Has been called");

}

}

}
 
Hi David,
Which version of foo() is bar() going to call? I'm not seeing what I
expected to see.

class A{}
class B : A{}
class C
{

// i bet on this call:
public void foo(A a){}

public void foo(B b){}

// add this:
public void foo(object o) {};
some function bar()
{
C c = new C();
A obj = new B();

c.foo(obj);

// add this:
c.foo((object) new B();

Compiler(or whatever it name) takes method with proper parameter
types. So if your object of class B is cast to A or object
then its better to call method with casted types.

Other thing is overriding methods of subclass...

Greetings

Marcin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top