Showing posts with label Constructor & Destructor Execution Order. Show all posts
Showing posts with label Constructor & Destructor Execution Order. Show all posts

Thursday, January 24, 2019

Sample Problem: C++ - Order of Execution of Constructors & Destructors Between a Parent & Child Class

You have a parent class that has a constructor and a non-virtual destructor, as well as a child class that inherits from the parent class. What is the execution order for the constructors and destructors?


  1. Parent constructor is called
  2. Child constructor is called
  3. Child destructor is called
  4. Parent destructor is called
Source Code
Source.cpp
#include "Parent.h"

#include "Child.h"
#include <iostream>

int main()
{
Child* testChild = new Child();
testChild->~Child();

int endInput;
std::cin >> endInput;

return 0;
}

Parent.h
#pragma once
#include <iostream>

class Parent
{
public:
Parent();
~Parent();
};

Parent.cpp
#include "Parent.h"

Parent::Parent()
{
std::cout << "Parent Constructor Called" << std::endl;
}

Parent::~Parent()
{
std::cout << "Parent Destructor Called" << std::endl;
}

Child.h
#pragma once
#include "Parent.h"
#include <iostream>

class Child : Parent
{
public:
Child();
~Child();
};

Child.cpp
#include "Child.h"

Child::Child()
{
std::cout << "Child Constructor Called" << std::endl;
}

Child::~Child()
{
std::cout << "Child Destructor Called" << std::endl;
}

Console Output