Which is a better C++ class design?

I have two classes which resemble the following.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Hand
{
public:
  func1();
  func2();
  ...
  func20();
private:
  Hand();
  ~Hand();
  Hand(const Hand& that);
  void operator=(Hand const&);
friend class Body;
};

class Body
{
  Body();
  ~Body();
  Hand * const &left_hand;
  Hand * const &right_hand;
private:
  Hand * _left_hand;
  Hand * _right_hand;
};

Body::Body()
:left_hand(_left_hand)
:right_hand(_right_hand)
{
  _left_hand = new Hand();
  _right_hand = new Hand();
};


This follows the Hand/Body relation-
1) User cannot create/delete a Hand object.
2) User cannot create a copy of the Hand object belonging to the Body.
3) User cannot modify the left hand and right hand pointers of the Body object.

However, my colleagues say that to allow the user to directly call methods of a member object (in this case body->left_hand->method1()) is a bad design.

One suggestion was to use a getter funtion eg getLeftHand() which returns "hand * const" instead of a read only public variable left_hand.

Another was to create wrapper functions for each Hand functions like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Body
{
  Body();
  ~Body();
  leftHandfunc1();
  rightHandfunc1();
  leftHandfunc2();
  rightHandfunc2();
  ...
  leftHandfunc20();
  rightHandfunc20();
private:
  Hand * _left_hand;
  Hand * _right_hand;
};


And
1
2
3
4
Body::leftHandfunc1()
{
  _left_hand->func1();
}

However, as you can see, 20 methods of Hand equals 40 wrapper functions in Body. And this list is expected to grow. Should I go with this approach?

Is there any better alternative?
Last edited on
closed account (48bpfSEw)

I wrote about a simple database structure modell in this thread

http://www.cplusplus.com/forum/beginner/191199/


In your case my approach would look so:

CLASSES:
Body
Hand

CLASS_CONNECTIONS:
Body has Hand (of Type: left|right|middle?|etc.)



Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Body {
  ...
}

class Hand {
  ...
}

Class Body_Hand_Relation {
  
  typedef HandType {
    leftHand,
    rightHand,
  }

  Body      body;
  Hand      hand;
  HandType  handtyp;
}




If this is a better alternative?

I think "yes", because this modell separates the classes and connections and hold them separat (no friends etc.) This architecture is simple and wide open. If a system is too entangled (fixed connected with each other) it is to hard or mostly imposible to bring it in a new form. e.g. what if the organism has 3 or 4 or more hands?

KISS : keep it simple and stupid is the maxim for a better coding.

Topic archived. No new replies allowed.