The difference between inheritance and composition in C++ is explained in detail

  • 2020-04-02 01:37:49
  • OfStack

The "inheritance" feature of C++ can improve the reusability of programs. Because "inheritance" is so useful and easy to use, it is important to prevent the misuse of "inheritance". We have some rules for using inheritance:

1. If class A and class B are unrelated, B should not inherit from A in order to make B more functional.

Do not feel that "do not eat white do not eat", let a healthy healthy young man without reason to eat ginseng body.

Ii. If it is necessary to use the function of A in class B, two situations should be considered:

(1) if logically B is A kind of A, B is allowed to inherit the functions of A. For example, Man is a kind of Human and Boy is a kind of Man. Then the class Man can be derived from the class Human, and the class Boy can be derived from the class Man. The sample program is as follows:


class Human
{
 ... 
};
class Man : public Human
{
 ... 
};
class Boy : public Man
{
 ... 
};

(2) if logically A is A part of B, B is not allowed to inherit from A's functions, but to combine A with something else to make B. For example, the Eye, Nose, Mouth, and Ear are part of the Head, so a Head should be a combination of the Eye, Nose, Mouth, and Ear, not a derivative. The sample program is as follows:


class Eye
{
public:
  void Look(void);
};
class Nose
{
public:
  void Smell(void);
};
class Mouth
{
public:
  void Eat(void);
};
class Ear
{
public:
  void Listen(void);
};
//Correct design, lengthy process
class Head
{
public:
  void Look(void) { m_eye.Look(); }
  void Smell(void) { m_nose.Smell(); }
  void Eat(void) { m_mouth.Eat(); }
  void Listen(void) { m_ear.Listen(); }
private:
  Eye m_eye;
  Nose m_nose;
  Mouth m_mouth;
Ear m_ear;
};
 If you allow Head  from Eye , Nose , Mouth , Ear  Derived from, so Head  Will automatically have Look , Smell , Eat , Listen  These features: 
//Wrong design
class Head : public Eye, public Nose, public Mouth, public Ear
{
};

The above program is short and runs correctly, but the design is wrong. This leads to the argument that many programmers make design mistakes because of the temptation to "inherit."


Related articles: