I'm somewhat new to programming and I have a question about classes, inheritance, and polymorphism in C#. While learning about these topics, occasionally I'll come across code that looks something like this:
Animal fluffy = new Cat(); // where Animal is a superclass of Cat*
This confuses me, because I don't understand why someone would create a variable of type Animal to store an object of type Cat. Why wouldn't a person simply write this:
Cat fluffy = new Cat();
I do understand why it's legal to store a child object in a parent type variable, but not why it's useful. Is there ever a good reason to store a Cat
object in an Animal
variable vs. a Cat
variable? Can a person give me an example? I'm sure it has something to do with polymorphism and method overriding (and/or method hiding) but I can't seem to wrap my head around it. Thanks in advance!
No, it is not possible. Consider a scenario where an ACBus is a derived class of base class Bus.
One reason for this could be that BaseClass is abstract (BaseClasses often are), you want a BaseClass and need a derived type to initiate an instance and the choice of which derived type should be meaningful to the type of implementation.
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
The shortest example I can give you is if you want a list of all animals
List<Animal> Animals = new List<Animal>();
Animals.Add(new Cat());
Animals.Add(new Dog());
If you have ever created a project using Winforms, you will have already used something similar since all controls derive from Control
. You will then notice that a Window has a list of controls (this.Controls
), that allows you to access all child controls on a window at once. I.E to hide all controls.
foreach(var control in this.Controls)
control.Hide();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With