Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating variable of type <base class> to store <derived class> object in C# [closed]

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!

like image 281
dhughes01 Avatar asked Apr 19 '14 16:04

dhughes01


People also ask

Can we create a derived class object from base class?

No, it is not possible. Consider a scenario where an ACBus is a derived class of base class Bus.

Why would one create a base class object with reference to the derived class?

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.

What can hold the address of a pointer to the base class object derived class object?

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.


1 Answers

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();
like image 174
Sayse Avatar answered Oct 22 '22 11:10

Sayse