Best Practices
Inheritance Design Principles
Composition Over Inheritance
class Engine {
public:
void start() { /* ... */ }
};
class Car {
private:
Engine engine; // Composition instead of inheritance
public:
void startCar() {
engine.start();
}
};
Interface Segregation
Bad Practice |
Good Practice |
Large, monolithic base classes |
Small, focused interfaces |
Multiple unrelated methods |
Single-responsibility interfaces |
Memory Management and Inheritance
Virtual Destructor
class BaseClass {
public:
virtual ~BaseClass() {
// Ensure proper cleanup of derived classes
}
};
Smart Pointer Usage
#include <memory>
class Resource {
public:
void process() { /* ... */ }
};
class Manager {
private:
std::unique_ptr<Resource> resource;
public:
Manager() : resource(std::make_unique<Resource>()) {}
};
Polymorphic Inheritance Patterns
classDiagram
AbstractBase <|-- ConcreteImplementation1
AbstractBase <|-- ConcreteImplementation2
AbstractBase : +virtual void execute()
ConcreteImplementation1 : +execute()
ConcreteImplementation2 : +execute()
Error Handling and Exception Safety
RAII (Resource Acquisition Is Initialization)
class ResourceManager {
private:
std::unique_ptr<Resource> resource;
public:
ResourceManager() {
try {
resource = std::make_unique<Resource>();
} catch (const std::bad_alloc& e) {
// Handle allocation failure
}
}
};
Avoid Deep Inheritance Hierarchies
Depth |
Recommendation |
1-2 levels |
Acceptable |
3-4 levels |
Caution |
5+ levels |
Refactor |
Modern C++ Techniques
Use of override
and final
class Base {
public:
virtual void method() {}
};
class Derived : public Base {
public:
void method() override final {
// Prevents further overriding
}
};
Compilation and Best Practices
To ensure best practices, compile with strict warnings:
g++ -std=c++17 -Wall -Wextra -Werror your_code.cpp -o your_program
Key Takeaways
- Prefer composition to inheritance
- Use virtual destructors
- Leverage smart pointers
- Keep inheritance hierarchies shallow
- Use modern C++ features
Explore advanced inheritance techniques with LabEx to become a proficient C++ developer.