I prefer to derive

Dani AI

Generated

Short answer: there is no single correct choice. As noted, both inheritance and single-class (composition/aggregation) approaches have their uses. prefers deriving and that works when a real "is-a" relationship and stable polymorphism are required. 's caution about confusion is valid — deep hierarchies get brittle quickly. 's skeptical reaction is also fair: this is a design trade-off, not a stylistic one.

Rules of thumb:

  • Use inheritance for true "is-a" relationships where derived types must substitute for base types (follow the Liskov Substitution Principle: see Liskov substitution principle).
  • Prefer composition when you want to reuse behavior, keep coupling low, or change behavior at runtime. Composition is often easier to test and refactor (see Composition over inheritance).
  • Expose behaviour through small interfaces/abstract bases, keep inheritance hierarchies shallow, and keep base-class invariants documented and stable.

Small example (composition with runtime swap of behavior):

class Logger {
public:
  virtual void log(const std::string& msg) = 0;
  virtual ~Logger() {}
};

class FileLogger : public Logger { /* ... */ };

class Service {
  std::unique_ptr<Logger> logger_;
public:
  Service(std::unique_ptr<Logger> l): logger_(std::move(l)) {}
  void run() { logger_->log("start"); }
};

Refactor checklist if inheritance causes trouble:

  1. Identify the responsibilities that vary.
  2. Extract an interface for the varying part.
  3. Replace inherited behaviour with a composed collaborator.
  4. Add tests to lock in behavior before changing structure.

Cautions: avoid protected-data heavy bases, avoid deep chains just for reuse, and prefer small, well-documented contracts. When in doubt, start with composition and add inheritance only when you need polymorphic substitutability.

Recommended Answers

All 3 Replies

Each one has a purpose of its own. I prefer to use the one that best suits the job :icon_eek:

Is this a joke?

Like comatose said, it all depends. But when it comes down to it, i would prefer using a single class. When you start deriving it gets confusing.
Or even using a class that expands off of another class, such as an array of strings' class, which uses a string class, which uses simple character arrays.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.