2

Can anyone explain what "HAS-A" and "IS-A" means between two class.

An example would helpful.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
kovenzhang
  • 85
  • 1
  • 1
  • 4

3 Answers3

6
  • A car is-a vehicle
  • A car has-a steering wheel

Eg:

class SteeringWheel
{};

class Vehicle
{
    virtual void doStuff() = 0;
};

class Car: public Vehicle
{
    SteeringWheel  sWheel;
    virtual void doStuff();
};
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 1
    I struggled for a decent example and actually thought about this, but I'd tend to put the steering wheel further up the hierarchy (so it covers trucks and some boats, for instance). – paxdiablo Mar 13 '12 at 02:32
  • @Loki Astari Thanks very much for you example. Is there are only the two relationships between classes??:) – kovenzhang Mar 13 '12 at 05:15
  • @kovenzhang: This is just a simple rule of thumb to help you think about it. In the real world things are never quite as cut and dried and the line can be blurry and there are other ways of looking at things. But this is a very good technique to put you at a starting point for thinking about the problem at hand. – Martin York Mar 13 '12 at 06:29
3

In the object-oriented world, a class can be something or it can contain something.

For example, a Queue class may be a sub-class of a LinkedList class (since a linked list can certainly be used to implement a queue). That is an is-a relationship. Everything that you can do to the linked list, you should be able to do to the queue.

However, the queue class may also hold other information such as the number of items in the linked list (for efficiency).

To that end, it may also define a member variable called size. That would be a has-a relationship - the queue is not a subclass of the integer, it simply contains an integer.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

These are two common forms of relationship between two classes.

The HAS-A relationship refers to a class X which has a class Y as a component, probably expressed by placing an instance of class Y as an attribute in every object of class X.

The IS-A relationship refers to a class W which is a class Z, probably because class W is a subclass of class Z, or has class Z somewhere in its inheritance graph. Code which knows how to deal with instances of class Z should be able to handle instances of class W with no code changes required.

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106