Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance only for code reuse c++

I have classes A and B. Now I need to write a new class C that will use some fields and methods in both A and B but not all of them. (I'll use about 50% of the stuff from A and B).

Right now I'm thinking about inheriting from both A and B. But that will make C contain a lot of fields and methods that have no meaning.

Basically I'm using inheritance only for code reuse purposes, because otherwise I will have to copy and paste many lines of code from A and B.

Is this practice really bad? Is there a different approach?

Thanks!

like image 961
user1657624 Avatar asked Sep 26 '12 21:09

user1657624


1 Answers

Inheritance doesn't have a concept of "is half of a", so it's definitely not the way to go here. It sounds like it's a prime case for composition.

It sounds like A and B have more than one "function" since half of them each are enough to compose a C.

I'm not sure this is applicable in your case, but consider breaking A into two parts, A1 and A2 with the required functionality for C in A1. Then do the same for B into B1 and B2.

A will then be a composition of A1 and A2, B will be a composition of B1 and B2 and C will be a composition of A1 and B1. None of them with any un-necessary functionality or data.

like image 169
Joachim Isaksson Avatar answered Sep 19 '22 23:09

Joachim Isaksson