class Animal
{
public void Foo() { Console.WriteLine("Animal::Foo()"); }
}
class Cat : Animal
{
public void Foo() { Console.WriteLine("Cat::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
Animal a;
a = new Cat();
a.Foo(); // output --> "Animal::Foo()"
}
}
The compiler warning says:
Cat.Foo hides the inherited member
However the output actually is from the base class. So to me it seems the other way around, the one I called is hidden by the one in the base class.
The output of your program is the
Animal
class implementation ofFoo
since the type of the reference isAnimal
and notCat
.If the reference was of type
Cat
, the output would be"Cat::Foo()"
.The
Foo
method of theCat
class is hiding theFoo
method of theAnimal
class because base classes can not and should not be aware of their derived classes, while derived classes are and must be aware of their base classes.To deliberately hide a member of the base class, use the
new
modifier. This will tell the compiler that the hiding is deliberate, and will suppress the warning.