I'm wondering if we could achieve composition goals through inheritance by keeping each class small and inheriting from multiple classes(java and c# doesn't support unfortunately)?
for example:
#include <iostream>
// Base class 1
class Base1 {
public:
void Method1() {
std::cout << "Method1 from Base1" << std::endl;
}
};
// Base class 2
class Base2 {
public:
void Method2() {
std::cout << "Method2 from Base2" << std::endl;
}
};
// Composite class inheriting from Base1 and Base2
class Composite : public Base1, public Base2 {
public:
void AdditionalMethod() {
std::cout << "AdditionalMethod in Composite" << std::endl;
}
};
int main() {
Composite c;
c.Method1(); // Calling Method1 from Base1
c.Method2(); // Calling Method2 from Base2
c.AdditionalMethod(); // Calling AdditionalMethod from Composite
return 0;
}
can we say we eliminate inheritance cons in this way?
Yes, multiple inheritance can achieve composition by combining the functionality of base classes. However in this way the derived class become tightly coupled with its base classes and in situations where both base classes have methods with the same name, you would need to explicitly specify which base class's method to call. This can lead to code that is harder to maintain since changes in the base classes' could impact the behavior of the derived class.
You would prefer to use composition and dependency injection whenever possible. Composition allows you to combine different components achieving modularity while dependency injection helps decouple the dependency of a class by injecting them from external sources. This allows for better testability, maintainability, and flexibility in your code.