Call order of constructors for C + + aggregation relationship classes

Source: Internet
Author: User

, which represents an aggregation relationship

The following is a simple code to implement

1 #pragma once2class  Engine3{4public:  5    Engine (); 6     ~Engine (); 7 };
Engine.h
1#include <iostream>2#include"Engine.h"3 using namespacestd;4 5 Engine::engine ()6 {7cout <<"Call Constructor: Engine ()"<<Endl;8 }9 Tenengine::~Engine () One { Acout <<"Call destructor: ~engine ()"<<Endl; -}
Engine.cpp
1 #pragmaOnce2#include"Engine.h"3 4 classCar5 {6  Public:7 Car ();8~Car ();9 Private:Ten Engine M_ecar; One};
Car.h
1#include <iostream>2#include"Car.h"3 using namespacestd;4 5 Car::car ()6 {7cout <<"Call Constructor: Car ()"<<Endl;8 }9 Tencar::~Car () One { Acout <<"Call destructor: ~car ()"<<Endl; -}
Car.cpp

It can be seen that the order of the constructor call of the object is like we build the car, first build a good engine and other parts to assemble the car, the call of the destructor and the disassembly of the car, first open the outermost, and then the inside.

Call order of constructors for C + + aggregation relationship classes

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.