Search This Blog

Showing posts with label CPP. Show all posts
Showing posts with label CPP. Show all posts

Friday, April 12, 2013

How To Find 64-bit Operating System?

During installation of a software we copy the files based on 32-bit or 64-bit operation system.

For example,
In 64-bit OS,  we install 32-bit applications in to "C:\Program Files (x86)" folder and 64-bit into "C:\Program Files" folder by default.

Like that we load different DLLs(based on compilation method as 32 or 64 bit) based on the OS architecture to improve the speed of the process.

The following function code helps you to find whether OS installed is 32 or 64-bit Operating System.



BOOL Is64BitOS()
{
    typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
    PGNSI pGNSI;
    SYSTEM_INFO sysinfo;
    ZeroMemory(&sysinfo, sizeof(SYSTEM_INFO));
    pGNSI = (PGNSI) GetProcAddress(
      GetModuleHandle(TEXT("kernel32.dll")), 
      "GetNativeSystemInfo");

    if(NULL != pGNSI)
    {
      pGNSI(&sysinfo);
    //GetNativeSystemInfo(&sysinfo);
    if(PROCESSOR_ARCHITECTURE_AMD64==sysinfo.wProcessorArchitecture)
        return TRUE;
    else
        return FALSE;
    }
    else
        return FALSE;
}

Extract All Digits From A String

Sometimes we may need to extract only digits from a string.

For example,
When we display a phone number we display as 001-00-100-200, some thing like that.
but when we save this number is a database as integer, then we need to remove hyphen and other characters.

In such situation we can use this following function.
 
 

CString GetAllDigits(LPCSTR lpTxt)
{
    CString csDigits;
    for(;*lpTxt!='\0'; lpTxt++)
    {
        if(*lpTxt>=48 && *lpTxt <58)
        {
            csDigits += *lpTxt;
        }
    }
    return csDigits;
}

Count Digits, Alphabets, Special Characters and Total number of characters

Some software have option to find the number of digits, alphabets, special characters and total number of  characters.

This type of functions are helpful is parsing texts. This function uses the ASCII values of each characters and gives the count.  Zip code in Canada has alphabets and numbers for such type of validation, we can use this function.

This function accept a string as pointer to a character and  give the count as reference.



unsigned int CountLetters(LPCTSTR lpTxt, unsigned int &nAlphabetCount, unsigned int &nDigitCount, unsigned int &niSpecialCharCount)
{
    unsigned int nLength =0; 
    nAlphabetCount = 0;
    nDigitCount = 0;
    niSpecialCharCount =0;

    for(;*lpTxt!='\0'; lpTxt++)
    {
        if( (*lpTxt>='a'  && *lpTxt <='z') || (*lpTxt>='A'  && *lpTxt <='Z'))
        {
            nAlphabetCount++;
        }
        else if(*lpTxt>=48 && *lpTxt <58)
        {
            nDigitCount++;
        }
        else if( *lpTxt < 127 && *lpTxt>32 && *lpTxt != 160)
        {
            niSpecialCharCount++;
        }
        nLength++;
    }
    return nLength;
}

Counting Number Of Digits In C++

We validate phone numbers, Zip code, credit card numbers, etc using number of digits.

How to get the number of digits?

 When we have a number as the  string  then we can find the count by using the ASCII value.
ASCII value of '0' is 48 and '9' is 57. we have to check the ASCII of each character and if it matches the numerical range then we have increase the count.

Following function helps us to count the number of digits



unsigned int CountDigits(LPCTSTR lpTxt)
{
    unsigned int nCount =0;
    for(;*lpTxt!='\0'; lpTxt++)
    {
        if(*lpTxt>=48 && *lpTxt <58)
            nCount++;
    }
    return nCount;
}

Deleting A Directory in C++

When we delete a directory programatically we can't delete it when there is some files or folders inside the directory.  We can delete only the empty folders.

Otherwise, We usually delete  recursively search and delete all files and then we delete all folders and finally we delete the folder which we want to delete.

But the following code snippet uses shell operation and delete the directory directly without any recursive function.

It is faster than the recursive function.

 
bool DeleteDirectory(LPCTSTR lpszDir)
{
 int len = _tcslen(lpszDir);
 TCHAR *pszFrom = new TCHAR[len+2];
 _tcscpy(pszFrom, lpszDir);
 pszFrom[len] = 0;
 pszFrom[len+1] = 0;

 SHFILEOPSTRUCT fileop;
 fileop.hwnd   = NULL;    // no status display
 fileop.wFunc  = FO_DELETE;  // delete operation
 fileop.pFrom  = pszFrom;  // source file name as double null terminated string
 fileop.pTo    = NULL;    // no destination needed
 fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user

 

 fileop.fAnyOperationsAborted = FALSE;
 fileop.lpszProgressTitle     = NULL;
 fileop.hNameMappings         = NULL;

 int ret = SHFileOperation(&fileop); 
 delete [] pszFrom;  
 return (ret == 0);
}

Tuesday, February 19, 2013

Why a constructor cannot be declared as virtual?

A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor.

We can't override a constructor. When any method is declared as virtual it should be overridden in its derived class. Since constructor is used for initializing the variables and if declare a constructor as virtual it can’t be overridden.

Singleton Class in C++


Singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Application:
  • This pattern can be used in "Database class" to that insert and retrieve record's in threads.
  • Can be used in Logger class.
How to create?
  • Define the constructor as private.
  • Declare copy constructor and Assignment operator as private to avoid creating copy of object
Sample 1( Allocating memory dynamically with new operator):

 
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;


class Singleton
{
private:
    static Singleton *m_ptrInstance;
    Singleton(){};
    Singleton(Singleton const&);             
    void operator=(Singleton const&);

public:
    static Singleton* GetInstance()
    {
        if(m_ptrInstance==NULL)
        {
            m_ptrInstance=new Singleton();
        }
        return m_ptrInstance;
    }
    void Display()
    {
        cout<<"This is singleton class"; 
    }
};
Singleton* Singleton::m_ptrInstance=NULL;


int _tmain(int argc, _TCHAR* argv[])
{
    //How to call    
    Singleton::GetInstance()->Display();
    getch();
    return 0;
}
 
Sample 2( Without allocating memory dynamically with new operator):

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;


class Singleton
{
private:
    Singleton(){}
    Singleton(Singleton const&);             
    void operator=(Singleton const&);

public:
    static Singleton& GetInstance()
    {
        static Singleton _instance;
        return _instance;
    }
    void Display()
    {
        cout<<"This is singleton class"; 
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    //How to call    
    Singleton::GetInstance().Display();
    getch();
    return 0;
}

Thursday, January 3, 2013

How to Intialize the Array elements value to NULL?

Usually we initialize the dynamically allocated array values to NULL using the memset.

We can do it while we allocate memory itself, by adding parenthesis ()  after the size.

Sample Code snippet:
 
int* nIntializedArray=new int[3]();

Example:


#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i=0;
    cout<<"Uninitialazied Arrary of int* \r\n\r\n";

    int* nUnIntializedArrayptr=new int[3];
    for( i=0; i<3; i++)
    {
        cout<<nUnIntializedArrayptr[i]<<"\r\n";
        
    }
    delete[] nUnIntializedArrayptr;
    cout<<"\r\n\r\n";


    cout<<"Initialazied Arrary of int* \r\n\r\n";
    int* nIntializedArray=new int[3]();
    for( i=0; i<3; i++)
    {
        cout<<nIntializedArray[i]<<"\r\n";
        
    }
    delete[] nIntializedArray;


    cout<<"UnInitialazied char* \r\n\r\n";
    char* sztxt=new char[3];
    cout<<sztxt<<"\r\n";    
    delete[] sztxt;

    cout<<"Initialazied char* \r\n\r\n";
    char* szIntialTxt=new char[3]();
    cout<<szIntialTxt<<"\r\n";    
    delete[] szIntialTxt;


    getch();
    return 0;
}
 
 

How to find the size of a dynamically allocated array?

Usually when we pass a pointer to an array to another function, we pass its size also as the parameter.
Which is not required, if the array is dynamically allocated.

We can find the size of a dynamically allocated array using _msize() function.


    TCHAR *szTxt=new TCHAR[256];
    int nArraySize=0;
    nArraySize=    _msize(szTxt)/sizeof(TCHAR);


Example:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

void GetIntPtrArray(int* ptrInt)
{
    //To find size of Array
    int nSize=_msize(ptrInt)/sizeof(int);
    cout<<"\r\nThe size of the Integer Array is "<<nSize;
}

void GetCharPtrArray(char* ptrchr)
{
    //To find size of Array
    int nSize=_msize(ptrchr)/sizeof(char);
    cout<<"\r\nThe size of the Char Array is "<<nSize;
}
int _tmain(int argc, _TCHAR* argv[])
{
    int *nArr=new int[10];
    GetIntPtrArray(nArr);

    char *szTxt=new char[256];
    GetCharPtrArray(szTxt);

    getch();
    return 0;
}
 
 

Thursday, September 20, 2012

Virtual destructor

One of the common C++ interview question is what is virtual destructor? Or what is the use of virtual destructor?
You are assigning a derived class object to a base class pointer and deleting the base class pointer.
If the base class destructor is not declared as virtual, then derived class destructor won’t get called.
If you are deleting some variables allocated heap memory in derived class destructor, then it will cause memory leak.



// CPPSamples.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
    public:
    Base()
    {
        cout<<"\n Base class Constructor\r\n";
    }
    ~Base()
    {
        cout<<"\n Base class Destructor\r\n";
    }

};
class Derived:Base
{
public:
    Derived()
    {
        cout<<"\n Derived class Constructor\r\n";
    }
    ~Derived()
    {
        cout<<"\n Derived class Destructor\r\n";
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Base *ptr=(Base*)new Derived();
    delete ptr;
    getch();
    return 0;
}
 

 


 
If the base class Destructor is virtual then,
 
// CPPSamples.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
    public:
    Base()
    {
        cout<<"\n Base class Constructor\r\n";
    }
    virtual ~Base()
    {
        cout<<"\n Base class Destructor\r\n";
    }

};
class Derived:Base
{
public:
    Derived()
    {
        cout<<"\n Derived class Constructor\r\n";
    }
    ~Derived()
    {
        cout<<"\n Derived class Destructor\r\n";
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Base *ptr=(Base*)new Derived();
    delete ptr;
    getch();
    return 0;
}