instance of class A vs class B derived from class A

There are two ways to access the members of class A inside class B:

1) Making an instance of class A in class B
2) Deriving class B from class A

So what is the basic difference in both ways as we can do same kind of work with both ways?
Public inheritance implies an "is a" relationship.
Composition (putting A inside of class B) implies a "has a" relationship.


class Car might derive from class Vehicle... because a Car "is a" vehicle. The parent class is a more generic term, whereas derived classes get more and more specific.

Another contrived example of a class hierarchy might be:
Animal -> Mammal -> Dog -> Poodle

Where 'Animal' is the top-most ancestor and Poodle is the child.

The reason this "is a" relationship persists is because you can treat any derived class as if it were an instance of its parent. This is the nature of polymorphism:

1
2
3
4
5
6
7
8
Poodle myDogMax;
myDogMax.doSomethingOnlyPoodlesCanDo();


Dog& foo = myDogMax; // since a Poodle is a Dog, you can have a Dog reference that
   // refers to a Poodle.

foo.doSomethingThatAllDogsCanDo();



"Has a" relationships differ because the idea of an object containing something else does not impact its outward usage. Back to the vehicle example.... Car might derive from Vehicle. And Car might also have an Engine object. A car is not an engine... nor is an engine a car.... so using inheritance there does not make sense.
Topic archived. No new replies allowed.