Index

C & C++ Programming - Uninitialzed Objects

//////////////////////////////////////////////////////////////////////////////////////////////////
// Programmer: SG //
// Description: //
//////////////////////////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"

int g_nCount = 20;

class CMyClass
{
public:
  CMyClass();
  ~CMyClass();

private:
  int m_nCnt;
  static int s_nCount; // An static variable can be defined as private
        // A static const can be initialise within class defintion

public:
  void GetStatement();
  static void GetStatementThruStaticFunc();
};

int CMyClass::s_nCount = 10;

CMyClass::CMyClass()
  : m_nCnt(0)
{
  cout << "CTOR Called\n";
}

CMyClass::~CMyClass()
{
  cout << "DTOR Called\n";
}

void CMyClass::GetStatement()
{
  cout << "Hello!!!" << endl;

  // Correct
  // A static member and global variable can be used in function
  // even if called through the obj which is not initialise.
  cout << "g_nCount = " << g_nCount << endl;
  cout << "s_nCount = " << s_nCount << endl;

  // Incorrect
  // if this is used in case of uninitialise object the program will crash.
  //m_nCnt++;
}

void CMyClass::GetStatementThruStaticFunc()
{
  g_nCount++;
  //s_nCount++;
  cout << "g_nCount = " << g_nCount << endl;
  cout << "s_nCount = " << s_nCount << endl;

  // m_nCnt++; // cann't access non static member
}

int _tmain(int argc, _TCHAR* argv[])
{
  CMyClass* pObj = NULL; // Will show warning (Uninitiallise)

  //////////////////////////////////////////////////////////////////
  // This will execute as during the declaration of an object //
  // memory space is initialise for functions, static variables //
  // and global variable but not for variable. //
  // If any of the variable is being used inside it will crash; //
  //////////////////////////////////////////////////////////////////

  pObj->GetStatement();
  CMyClass::GetStatementThruStaticFunc();
  return 0;
}
Index