interface and casting (second try)

  • Thread starter Thread starter anon
  • Start date Start date
A

anon

How can I do the following....

interface iface
{
int someMethod();
}

class c1 : iface
{
int someMethod() {return 10;}
}

class c2 : c1
{
int new someMethod() {return 20;}
}

class c3 : c1
{
int new someMethod() {return 30;}
}

class Test
{
int testMethod()
{
return testInterface(new c3());
}

int testInterface(iface i)
{
// in this case, returns 10
// as it stands now, i have to
// cast it to a c1, before it will
// return correct value;
return i.testMethod
}
}

If i pass in a c1, I would like to return 10, however if
I pass in a c3, I would like it to return 30. Right now,
when passing in a c3, it returns 10. This is not what I
expected, although I think i understand why this happens.

I would like to do this without have to figure out which
type was passed in... I would think that if I passed in a
c3, then c3's method would be called.. and not c1's
method.

Thanks
 
Well, I probably didn't show this correctly... I would
also like to hide "someMethod" from the user of my
class... but also make it available to the programmer of
my class... the only way to do this was to first
implement the interface, then derive from the implemented
interface.
 
Kurt Lange said:
Well, I probably didn't show this correctly... I would
also like to hide "someMethod" from the user of my
class... but also make it available to the programmer of
my class... the only way to do this was to first
implement the interface, then derive from the implemented
interface.

Which version of someMethod do you want to hide?

If the method is available as part of the public interface, you could
use explicit interface implementation, but it's really not nice IMO.
Basically you should remember Liskov's Substitutability Rule - simply
put, it's that any instance of a derived class should be able to be
used as if it were an instance of the base class. Google for the rule
for more information on it.

If you could give a more concrete example of what you're trying to do,
that would help.
 
Back
Top