Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a derived class from a base class constructor?

I have say 3 classes, Animal, Cat & Dog.

// calling code
var x = new Animal("Rex"); // would like this to return a dog type
var x = new Animal("Mittens"); // would like this to return a cat type

if(x.GetType() == typeof(Dog))
{
   x.Bark();
}
else
{
  x.Meow();
}


class Animal
{
   public Animal(string name)
   {
      // check against some list of dog names ... find rex
      // return Animal of type Dog.

      // if not...

      // check against some list of cat names ... find mittens
      // return Animal of type Cat.
   }
}

Is this possible somehow? If not is there something similar I can do?

like image 367
sprocket12 Avatar asked Aug 19 '13 13:08

sprocket12


People also ask

Can a constructor be derived from base class?

To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++

How can a constructor be used as a derived class?

Constructors in Derived Class in C++If the class “A” is written before class “B” then the constructor of class “A” will be executed first. But if the class “B” is written before class “A” then the constructor of class “B” will be executed first.

Can a base class be derived from another class?

Base Class: A base class is a class in Object-Oriented Programming language, from which other classes are derived. The class which inherits the base class has all members of a base class as well as can also have some additional properties.

Can a class be both a base class and a derived class?

A derived class can have only one direct base class.


1 Answers

What you are looking for is either a 'virtual constructor' (not possibe in C#) or the Factory pattern.

class Animal
{
   // Factory method
   public static Animal Create(string name)
   {
      Animal animal = null;
      ...  // some logic based on 'name'
          animal = new Zebra();

      return animal;
   }
}

The Factory method can also be placed in another (Factory) class. That gives better decoupling etc.

like image 164
Henk Holterman Avatar answered Sep 28 '22 04:09

Henk Holterman