Composition VS Inheritance

Why Composition is said to be good ahead of inheritance. I am just learning C++ and it was said inheritance can be handled only by expert programmers, but I dont see anything like that. Can some one give me an example. Thanks in advance.
Why Composition is said to be good ahead of inheritance. I am just learning C++ and it was said inheritance can be handled only by expert programmers


I don't know where you heard that, but neither of those statements are true.

Composition and inheritance are just different ways of expressing a relationship between objects.

Composition implies a "has a" relationship, whereas inheritance implies an "is a" relationship.

Example:

1
2
3
4
5
6
7
8
9
class Pet
{
  // composition: a Pet "has a" name
  string name;
};

class Cat : public Pet  // inheritance:  a Cat "is a" Pet
{
};
Topic archived. No new replies allowed.