Search⌘ K
AI Features

Compile-Time Polymorphism and Code Bloat

Understand the concept of compile-time polymorphism in D, which enables behavior-based type compatibility using templates. Learn the differences between compile-time and run-time polymorphism, and discover how repeated code generation from templates can lead to code bloat. This lesson helps you evaluate trade-offs between polymorphism approaches and manage program size effectively.

We'll cover the following...

Compile-time polymorphism

In object-oriented programming (OOP), polymorphism is achieved using inheritance. For example, if a function takes an interface as a parameter, it accepts objects of any class that inherits that interface.

Let’s recall an earlier example from a previous chapter:

D
import std.stdio;
interface SoundEmitter {
string emitSound();
}
class Violin : SoundEmitter {
string emitSound() {
return "♩♪♪";
}
}
class Bell : SoundEmitter {
string emitSound() {
return "ding";
}
}
void useSoundEmittingObject(SoundEmitter object) {
// ... some operations ...
writeln(object.emitSound());
// ... more operations ...
}
void main() {
useSoundEmittingObject(new Violin);
useSoundEmittingObject(new Bell);
}

useSoundEmittingObject() benefits from polymorphism. It takes a SoundEmitter so that it can be used with any type that is derived from that interface.

Since ...