0

I've the following classes :

class A{
  int x;
  int y;
  int z;
  public:
    int getX();
    int getY();
    int getZ();
  //...
}

class B{
  int x;
  int y;
  int z;
  double rotation;
}

class C{
  int x;
  int y;
  int z;
  double dir;
  double index;
}

classes B and C have class A parameters in common, Is it good practice to inherit from class A or using composite and storing an A object in B and C classes?

when inheriting from A class it's not necessary to re-implement A functions for B and C but everyone says that composite is better than inheritance! so which one is better?

Edit: suppose both conditions: is-a relation and otherwise, suppose I've class "Point" as "A" class mentioned and I've a gps data which has latitude, longitude and elevation and in some classes I want to add some coordinate information to it. it is not clear that gps data is a point or has a point!

abdolahS
  • 663
  • 12
  • 35
  • It depends. Is this code performance sensitive? Sometimes the heaviest compromises come about when you can't do things the ideal way because it's way too slow. – tadman Jul 09 '17 at 10:33
  • Inheritance represents a "is-a" relation, use it only if `B` and `C` is a `A`. Any derived class can be assigned to a base class, which would be highly hazardous if there is no such relation – Passer By Jul 09 '17 at 10:40
  • If those `...` are `setX(), setY(), setZ()` that directly assign to the members, you just implemented direct access in a verbose manner. That's not what encapsulation means. – StoryTeller - Unslander Monica Jul 09 '17 at 10:41

1 Answers1

4

It's up to your class definitions and the relations between base and inheited classes.

Let me tell you an example. Suppose there's a class defines a gun. A police officer or soldier may has a gun, but none of them are a gun. So, you better define police officer and soldier classes to have a gun class as their member. This usage of class inheit is so called 'has-a' relations.

However, if you want to define a new gun with special features, you can inherit the gun class and write some new functions which demonstrate the features. This is so called 'is-a' relations.

John Park
  • 1,644
  • 1
  • 12
  • 17