Inheritance and constructor order

A derived class gets everything its base class has and adds its own. The base part is always built first.

Time O(1)Space one objectCode C++, Python and C#
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 Dog
class 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 Dog

Tips

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.