Inheritance for reusing C ++ code only

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

Now I am thinking about inheriting from A and B. But this will make C contain a lot of fields and methods that have no meaning.

I mainly use inheritance only for code reuse, because otherwise I will have to copy and paste many lines of code from A and B.

Is this practice really bad? Is there any other approach?

Thank!

+5
source share
5 answers

" ", . , .

, A B "", , C.

, , A , A1 A2 C A1. B B1 B2.

A A1 A2, B B1 B2, C A1 B1. - .

+6

"".
, C A, B, A B.
, A B , , C , - C ( , A B ).
, -, .

+3

" ++" ( 34), , ++ - friend .

S.O.L.I.D OO - ; , , , - , .

, -, ( interface , # Java). .

class IDriveable
{
public:
    virtual void GoForward() = 0;
    virtual void GoBackward() = 0;
};

class Car : public IDriveable { /* etc. */ };
class Bus : public IDriveable { /* etc. */ };
class Train : public IDriveable { /* etc. */ };

, , Drivable, , , .
, TurnLeft Bus Car, Train, , TurnLeft , Bus Car.

  • , , , , /, .

, , , . , , .

- , virtual ( - , );

, std::function lambdas - , , .

+3

. , .

(private - , ):

class C
{
    A a;
    B b;
}

C A B, , C .

+2

, :

:

class A
{
  virtual void foo();
  virtual void bar();
};

class B
{
  virtual void biz();
  virtual void baz();
};

class C : public A, public B
{
  virtual void foo() { /* my stuff */ }
  virtual void biz() { /* my other stuff */ +

  // but I don't need bar or baz!
};

A B, C:

class core_A
{
  virtual void foo();
};

class A : public core_A
{
  virtual void bar();
};

class core_B
{
  virtual void biz();
};

class B : public core_B
{
  virtual void baz();
};

class C : public core_A, public core_B
{
  virtual void foo() { /* my stuff */ }
  virtual void biz() { /* my other stuff */ +

  // Great, I don't have bar or baz!
};
0
source

All Articles