Understanding the order of constructors and destructors

Share the Article

When a class design is very complex, then the order of call of constructors and destructors becomes very important. For instance, assume that there is a design where there are base classes, derived classes, multiple inheritance and member objects in these classes. Now, the calling constructors and destructors shall follow a specific order as shown below:

Constructor order

  1. Base class member objects (in order of occurrence inside  base class)
  2. Base class constructors (in order of specification for multiple inheritance)
  3. Derived class member objects (in order of occurrence inside derived class)
  4. Derived class constructor

Destructor order

  • This will be follow exactly opposite order followed by the constructor
#include <iostream> using namespace std; class Base1member { public: Base1member() { cout << "Base1member()" << endl; } ~Base1member(){ cout << "~Base1member()" << endl; } }; class Base2member { public: Base2member() { cout << "Base2member()" << endl; } ~Base2member(){ cout << "~Base2member()" << endl; } }; class Derivedmember { public: Derivedmember() { cout << "Derivedmember()" << endl; } ~Derivedmember(){ cout << "~Derivedmember()" << endl; } }; class Base1 { Base1member b1; public: Base1() { cout << "Base1()" << endl; } ~Base1(){ cout << "~Base1()" << endl; } }; class Base2 { Base2member b2; public: Base2() { cout << "Base2()" << endl; } ~Base2(){ cout << "~Base2()" << endl; } }; class Derived : public Base2, public Base1 { Derivedmember d; public: Derived() { cout << "Derived()" << endl; } ~Derived(){ cout << "~Derived()" << endl; } }; int main() { Derived dobj; }

The output is:

Base2member() Base2() Base1member() Base1() Derivedmember() Derived() ~Derived() ~Derivedmember() ~Base1() ~Base1member() ~Base2() ~Base2member()

No relation to constructor initializer list :

It’s also interesting to note that the order of constructor calls for member objects is completely unrelated to the order of the calls in the constructor initializer list. The order is determined by only one order which is how the member objects are declared in the class.

This is because, if the C++ compiler allows to change order of constructor calls due to its constructor initializer list then it will have side-effects. For example, a class may end up having two different constructor call sequences when such a class contains two different constructors.

However, then the destructor cannot know that which destructor order will be considered for properly destructing the objects. This will end up in a dependency problem.

Example of 2 constructors having different initializer list order:

there are 2 constructors in class MainFunda and both are specifying different order of initialization of member objects in constructor initializer lists. However, we will see that compiler will completely ignore such lists and follow the logical order explained above:

#include <iostream> //main header using namespace std;//for namespace class member1 { public: member1() { cout << "member1()" << endl; } ~member1(){ cout << "~member1()" << endl; } }; class member2 { public: member2() { cout << "member2()" << endl; } ~member2(){ cout << "~member2()" << endl; } }; class MainFunda { member1 m1; member2 m2; public: MainFunda() : m2(), m1() //Initialization Order#1 { cout << "MainFunda()" << endl; } MainFunda(int x) : m1(), m2() //Initialization Order#2 { cout << "MainFunda(int)" << endl; } ~MainFunda() { cout << "~MainFunda()" << endl; } }; int main() { MainFunda a1; MainFunda a2(8); }

The output shows same order of construction of member1 & member2 in both:

member1() member2() MainFunda() member1() member2() MainFunda(int) ~MainFunda() ~member2() ~member1() ~MainFunda() ~member2() ~member1()

Main Funda: The order of calls of constructors and destructors are exactly opposite to each other

Related Topics:

Parametrized constructor
Virtual Destructor & Pure Virtual Destructor
Smart Pointers: unique_ptr<T>
Diamond problem – Overhead of virtual base
Multiple Inheritance has multiple this pointers
Understanding multiple inheritance & virtual base classes
Understanding the copy constructor
What is an explicit constructor ?
Smart Pointers: shared_ptr <T> 
What is move constructor ?
What happens when exception thrown from a constructor?
Why a destructor should never throw exception?
Compiler Generated Destructor is always non-virtual
Which member functions are generated by compiler in class?
Understanding array version of new[] & delete[]

Share the Article

877 thoughts on “Understanding the order of constructors and destructors

  1. It’s appropriate time to make some plans for the future and it’s time to be happy. I have read this post and if I could I wish to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!* JJ’s Ducted Gas Heating Repairs and Installation * 162 Mitchell Rd, Lilydale VIC 3140 * 0412 531 821

  2. An attention-grabbing dialogue is value comment. I believe that you should write more on this subject, it may not be a taboo subject but usually people are not sufficient to speak on such topics. To the next. Cheers

  3. I’m writing on this topic these days, totosite, but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts.

  4. Nice blog here! Additionally your website rather a lot up fast! What host are you the usage of? Can I get your associate link for your host? I desire my website loaded up as fast as yours lol

  5. After I originally commented I clicked the -Notify me when new feedback are added- checkbox and now every time a remark is added I get 4 emails with the same comment. Is there any manner you’ll be able to take away me from that service? Thanks!

  6. An attention-grabbing discussion is worth comment. I believe that it’s best to write more on this subject, it won’t be a taboo subject however typically persons are not enough to speak on such topics. To the next. Cheers

  7. I have observed that of all sorts of insurance, medical insurance is the most questionable because of the turmoil between the insurance coverage company’s obligation to remain afloat and the buyer’s need to have insurance policies. Insurance companies’ profits on overall health plans are extremely low, thus some organizations struggle to profit. Thanks for the concepts you write about through this web site.

  8. I mastered more new stuff on this fat reduction issue. Just one issue is a good nutrition is vital if dieting. A huge reduction in junk food, sugary foods, fried foods, sweet foods, red meat, and whitened flour products could possibly be necessary. Having wastes harmful bacteria, and toxins may prevent objectives for shedding fat. While particular drugs momentarily solve the condition, the awful side effects will not be worth it, and in addition they never present more than a temporary solution. It is just a known fact that 95 of diet plans fail. Many thanks sharing your opinions on this site.

  9. I’m very happy to read this. This is the type of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this best doc.

  10. Thanks for your article. Another item is that to be a photographer includes not only problems in capturing award-winning photographs but hardships in acquiring the best photographic camera suited to your needs and most especially challenges in maintaining the caliber of your camera. This really is very real and evident for those photographers that are straight into capturing the particular nature’s captivating scenes — the mountains, the forests, the wild or perhaps the seas. Going to these daring places unquestionably requires a camera that can meet the wild’s nasty natural environment.

  11. By my examination, shopping for gadgets online may be easily expensive, nonetheless there are some principles that you can use to help you get the best bargains. There are often ways to locate discount specials that could make one to have the best technology products at the smallest prices. Thanks for your blog post.

  12. Hey There. I found your blog using msn. This is a really well written article. I?ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I?ll certainly return.

  13. I have learned some new things from your internet site about personal computers. Another thing I’ve always believed is that computer systems have become an item that each house must have for some reasons. They provide convenient ways to organize the home, pay bills, search for information, study, tune in to music and also watch tv series. An innovative approach to complete these types of tasks is to use a notebook computer. These personal computers are portable ones, small, effective and convenient.

  14. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an nervousness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike.

  15. Hi there, just became aware of your blog through Google, and found that it’s really informative. I?m going to watch out for brussels. I?ll be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  16. Thanks for expressing your ideas. A very important factor is that scholars have a choice between federal student loan along with a private student loan where it’s easier to choose student loan consolidation than through the federal education loan.

  17. What i do not realize is in truth how you’re not really a lot more neatly-favored than you may be right now. You’re so intelligent. You understand therefore considerably in terms of this topic, produced me in my view imagine it from so many numerous angles. Its like men and women don’t seem to be interested unless it?s one thing to accomplish with Lady gaga! Your own stuffs outstanding. At all times care for it up!

  18. Can I simply say what a relief to search out somebody who actually knows what theyre speaking about on the internet. You undoubtedly know methods to convey a problem to mild and make it important. Extra folks must learn this and perceive this aspect of the story. I cant consider youre not more common since you definitely have the gift.

  19. Thanks for your posting. I would also love to opinion that the very first thing you will need to conduct is verify if you really need repairing credit. To do that you need to get your hands on a duplicate of your credit score. That should never be difficult, considering that the government mandates that you are allowed to get one free copy of your real credit report per year. You just have to ask the right men and women. You can either look into the website with the Federal Trade Commission or contact one of the leading credit agencies straight.

  20. Hello there, You’ve performed an excellent job. I will definitely digg it and in my opinion suggest to my friends. I am confident they’ll be benefited from this site.

  21. Great work! This is the type of info that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my web site . Thanks =)

  22. One thing I would like to say is always that before getting more laptop memory, check out the machine in which it would be installed. In the event the machine is usually running Windows XP, for instance, the actual memory threshold is 3.25GB. Putting in above this would purely constitute some sort of waste. Make sure that one’s mother board can handle the upgrade quantity, as well. Thanks for your blog post.

  23. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but instead of that, this is magnificent blog. An excellent read. I’ll definitely be back.

  24. I was very happy to find this internet-site.I wished to thanks for your time for this excellent read!! I positively enjoying each little little bit of it and I have you bookmarked to take a look at new stuff you blog post.

  25. Great article. It is extremely unfortunate that over the last decade, the travel industry has had to take on terrorism, SARS, tsunamis, influenza, swine flu, as well as the first ever real global downturn. Through all of it the industry has really proven to be powerful, resilient and dynamic, finding new strategies to deal with hardship. There are continually fresh complications and the possiblility to which the marketplace must yet again adapt and reply.

  26. Thanks for this glorious article. One more thing to mention is that most digital cameras come equipped with some sort of zoom lens that allows more or less of your scene to get included by way of ‘zooming’ in and out. These changes in {focus|focusing|concentration|target|the a**** length tend to be reflected within the viewfinder and on huge display screen on the back of the actual camera.

  27. This is the precise blog for anybody who desires to seek out out about this topic. You notice a lot its almost arduous to argue with you (not that I really would want?HaHa). You positively put a brand new spin on a topic thats been written about for years. Nice stuff, just nice!

  28. Thanks for these guidelines. One thing I additionally believe is always that credit cards featuring a 0 rate often appeal to consumers together with zero interest, instant authorization and easy on-line balance transfers, nonetheless beware of the most recognized factor that can void your own 0 easy neighborhood annual percentage rate as well as throw anybody out into the poor house rapidly.

  29. These days of austerity as well as relative stress and anxiety about getting debt, lots of people balk against the idea of employing a credit card in order to make purchase of merchandise or perhaps pay for a holiday, preferring, instead just to rely on the particular tried as well as trusted means of making repayment – hard cash. However, if you possess cash on hand to make the purchase completely, then, paradoxically, that’s the best time to be able to use the card for several reasons.

  30. Good article. It is extremely unfortunate that over the last decade, the travel industry has already been able to to take on terrorism, SARS, tsunamis, bird flu virus, swine flu, plus the first ever true global economic collapse. Through everything the industry has proven to be solid, resilient as well as dynamic, discovering new solutions to deal with misfortune. There are always fresh issues and possibilities to which the industry must yet again adapt and reply.

  31. Everything information about medication. Everything what you want to know about pills.
    tadalafil 100mg
    safe and effective drugs are available. Medscape Drugs & Diseases.

  32. After I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any way you possibly can take away me from that service? Thanks!

  33. Everything about medicine. drug information and news for professionals and consumers.
    generic viagra sale
    Some are medicines that help people when doctors prescribe. Prescription Drug Information, Interactions & Side.

  34. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  35. I was curious if you ever considered changing the layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures. Maybe you could space it out better?
    https://essaywritingservicebbc.com

  36. Comprehensive side effect and adverse reaction information. Prescription Drug Information, Interactions & Side. https://avodart.science/# order generic avodart price
    Learn about the side effects, dosages, and interactions. Actual trends of drug.

  37. Ето и нещо, на което да обърнете внимание. Не е добре да се иска бонус, ако казиното, което го предлага, не е надеждно. Преди да се регистрирате, първо проверете ревюто и рейтинга на казиното. За най-високо оценените сайтове се насочете към нашия списък с най-добрите онлайн казина и ги прегледайте там. безплатни слотове без изтегляне и регистрация | Играйте слотове с кредитен телефон https://hectorfzpe108653.designi1.com/35344236/мобилното-покер Ако искате да се научите да играете Омаха, тогава изтеглете софтуера на PokerStars и се присъединете към безплатните игри на покер, за да се състезавате с други играчи онлайн. За разлика от игрите с истински пари, тук не рискувате нищо и имате възможност спокойно да научите всички правила на 6 Кард Омаха. Освен Микс 8-игри, предлагаме и много други варианти на покера. Вижте страницата ни с игри на покер, за да научите повече.

  38. The entire Watch City will undergo earth shaking changes, stomach cramp from diet pills and at that time, everything should start to go according to his own thoughts and plans, To be honest, when Jeff do prescribed diet pills work just revealed it, he was already above him, and even more so tamoxifen action C, CMX TRОІ1 or CMX TRОІ2 50 ng was cotransfected into TSA 201 cells with 100 ng of the reporter gene, TSHО± Luc, in the presence of 10 n m T 3 and increasing amounts of BPA

  39. Needed to put you that very small note to finally give many thanks the moment again just for the marvelous basics you have shown in this article. This has been really extremely generous with people like you to provide easily all some people would have sold as an e book to earn some bucks for their own end, certainly considering that you could have done it in case you considered necessary. These basics as well acted to become easy way to be aware that many people have the identical dream similar to my own to realize many more on the subject of this problem. Certainly there are several more enjoyable instances up front for folks who take a look at your site.

  40. I’m impressed, I need to say. Actually not often do I encounter a weblog that’s both educative and entertaining, and let me inform you, you could have hit the nail on the head. Your idea is outstanding; the difficulty is one thing that not enough individuals are speaking intelligently about. I’m very pleased that I stumbled across this in my search for something relating to this.

  41. When I read an article on this topic, safetoto the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

  42. Wilmer, USA 2022 05 20 22 08 09 Achete Levitra Anticholinesterase drugs also are useful in treating myasthenia gravis, in which progressive neuromuscular paralysis occurs as a result of the formation of antibodies against the acetylcholine receptor protein

  43. I am curious to find out what blog platform you are working with? I’m experiencing some minor security issues with my latest website and I’d like to find something more safe. Do you have any suggestions?

  44. wonderful post, very informative. I wonder why the other experts of this sector do not notice this. You should continue your writing. I’m sure, you have a huge readers’ base already!

  45. Thank you for another informative website. Where else could I get that type of information written in such an ideal way? I have a project that I am just now working on, and I have been on the look out for such info.

  46. In two other phase III trials, rolapitant in combination with granisetron and dexamethasone was well tolerated and superior to active control for the prevention of CINV during the at risk period 120 hours after administration of highly emetogenic cisplatin based chemotherapy lasix classification

  47. Situs Corporation Sitzmarks radiopaque markers study for constipation Sitzmarks test sivelestat injectable neutrophil elastase inhibitor for acute lung injury acute respiratory distress SiWa 114 wire by Cordis SJM Biflex annuloplasty ring SJM Biocor and Biocor Supra heart valves stents by St stromectol tablets Preferably, the dosage forms of the present invention can include 0 to 60 osmotic agents on a weight basis

  48. When I read an article on this topic, bitcoincasino the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

  49. Good – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your client to communicate. Excellent task.

  50. You actually make it seem so easy along with your presentation but I in finding this topic to be really something that I think I might never understand. It sort of feels too complicated and extremely large for me. I am having a look forward on your subsequent post, I will attempt to get the hang of it!

  51. You actually make it seem so easy together with your presentation however I in finding this matter to be actually something that I believe I would by no means understand. It seems too complex and extremely wide for me. I’m taking a look forward in your subsequent post, I will attempt to get the hold of it!

  52. Good V I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs as well as related info ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your client to communicate. Excellent task..

  53. Türkçe Dublaj Erotik Filmler; Altyazılı Erotik Filmler Arama Robotu; İletişim;
    En Son Eklenen Videolar Güncellendi. müjde
    ar sex filmi izle; IMDb: 0.0. Yerli Film 720p. Türk Yapımı Baldız Erotik Film İzle.
    Günün Filmi. Benimle Dalga Geçme 18+ Yeşilçam Erotik Filmi izle.

    IMDb: 0.0. Yapım yılı: 1976 Türkiye.