Reputation: 31
Im trying to make a Dog class, inheriting the Animal base class which has a constructor. Is there any way I can make the class Dog : Animal, but somehow use the Animal constructor with it? I looked at the similar questions, but I didnt get the answer I'm looking for.
class Class1
{
static void Main(string[] args)
{
Animal animal = new Animal("Spotty", 5, 4);
animal.Print();
}
}
class Animal
{
public string animalName;
public int animalAge;
public int animalLegs;
public Animal(string name, int age, int legs)
{
animalName = name;
animalAge = age;
animalLegs = legs;
}
public void Print()
{
Console.WriteLine("Name: " +animalName);
Console.WriteLine("Age: "+ animalAge);
Console.WriteLine("Number of Legs: " +animalLegs);
}
}
class Dog : Animal
{
//This wont work; there will be an error
}
Upvotes: 0
Views: 85
Reputation: 5506
You should either add a default constructor to Animal
, or add the necessary constructor to Dog
:
public Dog(string name, int age) : base(name, age, 4)
{
}
Upvotes: 2