Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I instance a class that inherits the values of an instance of a superclass?

Tags:

c#

oop

I am using C#, but I think this is a pretty generic OO question. Suppose I have a class called Animal, and it has properties like LegCount, EyeCount, HasFur, EatsMeat, etc.

Let's say I have an instance a of Animal. Suppose a has LegCount set to 4 and EyeCount set to 2.

Now, I'd like to create an instance d of type Dog, which inherits from Animal. I'd like to initialize d with all the values of a. I realize I could create a constructor or otherwise some other method that would take an Animal and spit out a new Dog with all the values copied in, but I was hoping there was some Object Oriented principle / trick that had me covered.

What I want to do, in plain English, is:

Create new Instance d of Dog, with all starting values from a. The key is "all", as opposed to specifying each property individually.

When you design a class that inherits from some other class, you don't need to list all the members it inherits. It just inherits all of them. So I am wondering if I can "inherit the values" on actual instances.

like image 873
Chris Avatar asked Nov 27 '22 18:11

Chris


1 Answers

The feature you want is called "prototype inheritance" or "prototype-oriented programming". C# does not support this feature, so you're out of luck there.

You might consider using a language that supports prototype inheritance if your architecture fundamentally needs this feature. JavaScript is the most commonly used prototype inheritance language.

Prototype inheritance can be quite tricky to get correct if you're not careful. If this subject interests you, see my article on some of the bizarre situations you can run into with prototype inheritance in JScript:

http://blogs.msdn.com/b/ericlippert/archive/2003/11/06/53352.aspx

like image 63
Eric Lippert Avatar answered Feb 17 '23 09:02

Eric Lippert