Construction and structure sequence of a single inheritance class

Source: Internet
Author: User

A single inherited derived class has only one base class or virtual base class. It is easy to determine the construction sequence based on four priority levels:
First, call the constructor of the virtual base class of the derived class. No matter whether the constructor of the virtual base class is listed, it will always be executed;
Then, the base class constructor of the derived class is called, regardless of whether the base class constructor is listed or not;
Then, initialize the data member or call the corresponding constructor in sequence according to the data member Declaration Order of the derived class. The object member will be constructed whether listed or not;
At the end, execute the constructor of the derived class.

The structure is the reverse order of the constructor.

# Include <iostream. h> # include <stdio. h> # include <stdlib. h> using namespace STD; Class A {int A; public: A (): A (8) {cout <a ;}// non-const member, you can assign a value to a (int x) again in the function body: A (x) {cout <;}~ A () {cout <a ;}}; Class B: A {// private inheritance, equivalent to Class B: Private A {int B, C; const int D; // B defines the read-only member D, so B must define the constructor a x, y, z; public: // initialize a, B, c, d, X, Y, and Z in the declared order. A and Z may not list B (int v): B (V), y (B + 2), x (B + 1), D (B), A (V) {c = V; cout <B <C <D; cout <"C"; // B, C can be assigned again }~ B () {cout <"D" ;}}; void main (void) {B z (1); // system ("pause "); // return 0 ;}



First Output 1. Call the constructor with parameters to construct a (v) // first construct the base class

Construct Data member B C Without Output

Construct x y and call the constructor with parameters to output 2 3

Construct Z call no parameter constructor output 8

Output The cout sentence 1 1 is B c d

Output C

Output D parses B c d

Output 8 3 2 1 parses z y x and base class

The structure and structure are in reverse order.

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: 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.