Inheritance and constructor order
A derived class gets everything its base class has and adds its own. The base part is always built first.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
A Dog is an Animal with extras. One object holds both the Animal fields and the Dog fields. : base(name) passes arguments up, and the Animal constructor finishes before the Dog constructor body starts.
Code
class Animal {
public:
string name;
Animal(string name) : name(name) {}
void eat() { cout << name << " eats\n"; }
};
class Dog : public Animal {
public:
string breed;
Dog(string name, string breed) : Animal(name), breed(breed) {}
void bark() { cout << name << " barks\n"; }
};
int main() {
Dog d("Rex", "Lab");
d.eat(); // inherited from Animal
d.bark(); // defined in Dog
}class Animal:
def __init__(self, name: str):
self.name = name
def eat(self): print(self.name, "eats")
class Dog(Animal):
def __init__(self, name: str, breed: str):
super().__init__(name); self.breed = breed
def bark(self): print(self.name, "barks")
d = Dog("Rex", "Lab")
d.eat() # inherited from Animal
d.bark() # defined in Dogclass Animal {
public string Name;
public Animal(string name) { Name = name; }
public void Eat() => Console.WriteLine(Name + " eats");
}
class Dog : Animal {
public string Breed;
public Dog(string name, string breed) : base(name) { Breed = breed; }
public void Bark() => Console.WriteLine(Name + " barks");
}
var d = new Dog("Rex", "Lab");
d.Eat(); // inherited from Animal
d.Bark(); // defined in DogTips
- Inheritance models "is a". If the honest sentence is "has a" (a Car has an Engine), use a field instead. That is composition.
- A C# class can inherit from only one class, but can implement many interfaces.
In the .NET library
Every class ultimately derives from System.Object, which is where ToString, Equals and GetHashCode come from. Mark a class sealed to stop others inheriting from it.