Research on multi-class inheritance and virtual inheritance

Source: Internet
Author: User

Problems arising from multiple inheritance
  
 
  1. #include <iostream>
  2. using namespace std;
  3. // 多继承产生的问题:如果一个继承的多继承有同一个父类,
  4. // 则父类的构造函数会被调用两次
  5. //////////////////////////////////////////////////////////////////////////
  6. // 多继承,多基类混乱的问题
  7. // 以下代码的结果
  8. /*
  9. 总类 A 构造函数被调用。。。
  10. 类 A1 构造函数被调用。。。
  11. 总类 A 构造函数被调用。。。
  12. 类 A1 构造函数被调用。。。
  13. 类 F 构造函数被调用。。。
  14. */
  15. class A
  16. {
  17. public:
  18. A()
  19. {
  20. cout << "总类 A 构造函数被调用。。。" << endl;
  21. }
  22. };
  23. class A1 :public A
  24. {
  25. public:
  26. A1()
  27. {
  28. cout << "类 A1 构造函数被调用。。。" << endl;
  29. }
  30. };
  31. class A2 :public A
  32. {
  33. public:
  34. A2()
  35. {
  36. cout << "类 A1 构造函数被调用。。。" << endl;
  37. }
  38. };
  39. class F :public A1, public A2
  40. {
  41. public:
  42. F()
  43. {
  44. cout << "类 F 构造函数被调用。。。" << endl;
  45. }
  46. };
  47. int main1()
  48. {
  49. F f;
  50. return 0;
  51. }
#

#虚继承解决多继承产生的问题

  
 
  1. #include <iostream>
  2. using namespace std;
  3. //////////////////////////////////////////////////////////////////////////
  4. // 使总基类虚继承,可避免因为多继承,多基类混乱的问题
  5. // 以下代码的结果
  6. /*
  7. 总类 A 构造函数被调用。。。
  8. 类 A1 构造函数被调用。。。
  9. 类 A1 构造函数被调用。。。
  10. 类 F 构造函数被调用。。。
  11. 请按任意键继续. . .
  12. */
  13. class AA
  14. {
  15. public:
  16. AA()
  17. {
  18. cout << "总类 A 构造函数被调用。。。" << endl;
  19. }
  20. };
  21. class AA1 : virtual public AA
  22. {
  23. public:
  24. AA1()
  25. {
  26. cout << "类 A1 构造函数被调用。。。" << endl;
  27. }
  28. };
  29. class AA2 :virtual public AA
  30. {
  31. public:
  32. AA2()
  33. {
  34. cout << "类 A1 构造函数被调用。。。" << endl;
  35. }
  36. };
  37. class FF :public AA1, public AA2
  38. {
  39. public:
  40. FF()
  41. {
  42. cout << "类 F 构造函数被调用。。。" << endl;
  43. }
  44. };
  45. int main()
  46. {
  47. FF f;
  48. return 0;
  49. }


From for notes (Wiz)

Research on multi-class inheritance and virtual inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.