|
-
December 3rd, 2009, 09:19 AM
#1
How to return an object of inherited class from abstract base class?
So for practice i'm designing a class library of Animals - cow, chicken, pig, duck. I made my base class "Animal" abstract and the functions within abstract as well. Other animals simply inherit class Animal.
Here's what i'm trying to accomplish and I'm not sure how:
I want to have the base class Animal to have a function called "GiveBirth()" which simply returns a new Animal, but of the type of animal it came from. Problem is, my class is abstract so i can't return an "animal", but i have to return a specific inherited animal.
Is there a way to use polymorphism so i can just return the correct animal?
This is a member function from my base class Animal:
Code:
public virtual Animal GiveBirth() // returns, if successful, 1 or more animals of same type.
{
Console.WriteLine("A new {0} has been born.", (this.GetType().ToString()).Substring((this.GetType().ToString().LastIndexOf('.')) + 1));
return new Animal(); // Won't work!
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|