Multiple inheritance constructor execution order in C + +

Source: Internet
Author: User

Code Listing 1:

1#include <cstdio>2#include <iostream>3 4 using namespacestd;5 6 classa{7      Public:8 A () {9cout<<"A"<<Endl;Ten         } One }; A classb{ -      Public: - B () { thecout<<"B"<<Endl; -         } - }; - classC: PublicB Publica{ + //class C:public A,public b{ -      Public: + C () { Acout<<"C"<<Endl; at         } - }; - intMain () { -  - c C; -     return 0; in}

Output:

Bac

Analysis:

Multiple inheritance is similar to single inheritance, and it is the base class constructor that executes first. Between multiple base classes, it executes from left to right when declared by a derived class.

Code Listing 2:

1#include <cstdio>2#include <iostream>3 4 using namespacestd;5 6 classa{7      Public:8 A () {9cout<<"A"<<Endl;Ten         } One }; A classb{ -      Public: - B () { thecout<<"B"<<Endl; -         } - }; - classC: PublicB Publica{ + //class C:public A,public b{ -      Public: + A; A C () { atcout<<"C"<<Endl; -         } - }; - intMain () { -  - c C; in     return 0; -}

Output:

BAAC

Analysis:

Execution order: base class constructor, initialize member variable, derived class constructor

Multiple inheritance constructor execution order in C + +

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.