Designing Unique IDs and Choosing Between Inheritance and Composition in C++
The article discusses how to give each class object a unique identifier, compares inheritance and composition for associating objects, and examines the trade‑offs of each approach using C++ examples, ultimately suggesting that the choice should depend on hierarchy depth and maintenance cost.
Problem 1: How to give every class object a unique ID in an elegant way?
One common solution is to create a manager class that provides an ID, e.g.:
struct Object {
int64_t GetId();
};To associate this Object with other classes there are two typical approaches:
1. Inheritance
///< Method 1: Inheritance
struct A : Object {};
struct B : Object {};2. Composition
///< Method 2: Composition
struct A {
int64_t GetId() { return obj_.GetId(); }
private:
Object obj_;
};The article asks which of these two methods is better.
Problem 2: In audio‑video systems the video usually contains an audio track, and both have a volume property. How should we expose a SetVolume operation for video?
Again, two possibilities are shown.
Composition version
struct Audio {
void SetVolume();
};
struct Video : Audio {};
struct Video {
void SetVolume();
private:
Audio audio_;
};Inheritance version
struct Audio {
void SetVolume();
};
struct Video : Audio {};The author provides several tips:
‘Has‑a’ relationships usually favour composition, while ‘Is‑a’ relationships usually favour inheritance.
Composition can lead to many exposed interfaces and higher maintenance cost.
Inheritance can create deep hierarchies that hurt readability and maintainability.
In practice the author argues that the rules are not absolute; if the inheritance depth is shallow (e.g., one level) and the cost of forwarding many methods is high, inheritance may be the pragmatic choice.
Ultimately, the decision between inheritance and composition should be guided by the concrete context, balancing the advantages of each technique rather than rigidly following a single dogma.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.