When Is Member Created and Deleted

The class members will be created before class constructor is called, and they will be deleted after class deconstructor is called.

#include <iostream>
#include <cassert>

using std::cout;
using std::endl;

void Debug(const char* str)
{
  cout << str << endl;
}

class MemberVal
{
public:
  MemberVal()
  {
    Debug("MemberVal()");
  }

  ~MemberVal()
  {
    Debug("~MemberVal()");
  }
};

class Demo
{
public:
  Demo()
  {
    Debug("Demo()");
  }

  ~Demo()
  {
    Debug("~Demo()");
  }

private:
  // MemberVal will be created before Demo() is called,
  // and it will be deleted after ~Demo is called.
  MemberVal mMemVal;
};

int main() {

  Debug("-- Test start --");
  {
    Demo d;
    Debug("Demo might do something ...");
  } // d will be deleted out of this scope
  Debug("-- Test End --");

  return 0;
}

The output is

-- Test start --
MemberVal()
Demo()
Demo might do something ...
~Demo()
~MemberVal()
-- Test End --

results matching ""

    No results matching ""