dynamic_cast throws unhandled exception during Reverse Polymorphism?

30 06 2008

What is Reverse Polymorphism?
Casting Base class object to derived class pointer is called Reverse Polymorphism or Inverse Polymorphism. Check the following code block.

// Base class.
class Base
    virtual ~Base() {}

// Derived class.
class Derived : public Base
    virtual ~Derived() {}

void CDialogDlg::OnButton4()
    // Base instance.
    Base* pBase = new Base;

    // Reverse Polymorphism. Cast Base Object to derived.
    Derived* pDerived = dynamic_cast<Derived*>( pBase );

While casting by using dynamic_cast, possible you may hit un-handled exception as follows.

Ideally dynamic_cast should return null, since its an invalid casting. But why its throwing un-handled exception? Is there something to do?

You’ve to enable RTTI. If RTTI is not enabled, it will throw un-handled exception for reverse polymorphism. For enabling RTTI,

1) Take project settings,
2) Take C/C++ tab.
3) In “C++ Language” category, enable RTTI. See the screenshot.

This is not a standard C++ behavior. This one is checked only in Visual C++ 6.0 compiler. You may or may not encounter the behavior in other Microsoft compiler version or in other compilers. So take care!

Targeted Audience – Intermediate.

How to generate the hash key of given data?

27 06 2008

Hashes are everywhere. Hash is small key generated from a bulk chunk of data. The hashes are useful in many ways. They are used for table lookups and data comparison. Yes! As you think now, hash table is one among them which utilizes hashes for high speed lookups. Well, thats a good, But how to generate the hash of a chunk of data?

You can use the function – HashData(). See the following code snippet.

#include "Shlwapi.h"
// Buffer for hash Key.
const int MAX_HASH_LEN = 256;
BYTE Hash[MAX_HASH_LEN] = {0};

// Chunk of Data.
char* pData = "Hello World";

// Generate Hash Key.
HashData( (LPBYTE) pData,
          strlen( pData),
          MAX_HASH_LEN );

Do you know that in real world, Hash means – “Chop and Mix”. Have a look at Wiki –

BTW, Don’t forget to add Shlwapi.lib to project settings. 🙂

Targeted Audience – Beginners.

Function call by using null pointer will crash?

26 06 2008

Crash on function call by using null pointer – The ultimate C++ Nirvana. 😉 Whether function call by null pointer always crash? Is it possible to call functions by using null pointer without crash? Check the following code snippet. Whether it will crash?

// Console Helper class.
class ConsoleHelper
    // Prints a line to console.
    void PrintLine()
        cout << "---------------" << endl;

// The one and only one Main.
int main(int argc, char* argv[])
    // Call the function by using null pointer.
    ConsoleHelper* pConsoleHelper = 0;

    return 0;

It won’t crash. Because in the function call we’re not accessing any member variables. Function call by using null pointers crash only if we’re accessing some member variables. Its because for every object function call, the object address is pushed to the function stack as “this” pointer. If the object pointer is null, then the “this” pointer also become null and hence the crash!

Null pointers are not that much bad! isn’t it? 😉

Targeted Audience – Intermediate.

Allocate CString on heap – Does that saves memory and improve performance?

24 06 2008

“Objects – The stack’s worst enemy. The stack is only indented for light weight datatypes such as int, float etc. So if you want to allocate a lot of objects, allocate on Heap. Or else stack will overflow”

This is the golden rules that beginners learn first, while stepping into professional C++ development. While considering objects, CString instances are the most common ones used in almost all MFC applications and for improving performance and for saving memory, usually we used to allocate it on heap. But, does that saves memory and improve performance? Well, its a myth. Want to know why?

First of all check the following code snippet and answer me, whether the message box will be shown or not?

// CString size == int size?
if( sizeof(CString) == sizeof(int))
    // I can't believe it.
    AfxMessageBox(_T("Am I dreaming?"));

Yes! It’ll be shown and the size of CString is just 4 bytes. Actually CString just contains LPTSTR as member. CString always allocate the string on heap. So while allocating CString itself on heap, you’re really degrading performance by extra heap allocation and more over you’ve to manage the pointer which can lead to memory leaks.

Don’t think that all objects are good candidates for heap. There can be exception like our CString. 😉

Targeted Audience – Intermediate.

How to watch vectors more easily?

23 06 2008

Everyone uses vectors and during debugging if we’ve to watch the elements, its a real headache. The usual method that follows is to quick watch the vector and we add index to the _First element. For instance, assume we’ve the vector generated by following code snippet.

// The String Vector.
vector<CString> StringVector;

// Add some strings to it.

For watching it, we quick watch and click the _First member of vector and adds an index to it to skip to the nth element. See the screenshot.

Is there any better way to watch the whole vector instead of this iteration?

Yes! you can. First you’ve to get the vector size by adding “StringVector.size()” to watch window. Then you’ll get the size. Now add “StringVector._First,size” to the watch window. That will show all the elements in that vector. Just see the screenshot.

You can evaluate the same expression in your quick watch window. Have fun!

Targeted Audience – Intermediate.

How to empty recycle bin programmatically?

21 06 2008

While processing or writing huge files to disk, its quite possible that disk will go out of space. To Squeeze and to get more disk space, its a good idea to clean the recycle bin. But how to do it programmatically?

You can use the api – SHEmptyRecycleBin(). See the code snippet below.

// Empty the recycle bin.
SHEmptyRecycleBin( NULL,
                   SHERB_NOCONFIRMATION |
                   SHERB_NOPROGRESSUI   |
                   SHERB_NOSOUND );

By modifying the options, you can show progress UI, Show confirmation dialog and play sound on finishing task. Just remove the unwanted flags.

Targeted Audience – Beginners.

How to list directories / files of a given path in your listbox easily?

19 06 2008

Assume you’ve a listbox and you want to fill all directories/files of a particular path to it. The usual method is iterate each file by FindFirstFile() and FindNextFile(), then add to listbox. Or any other cool tricks to do the same more easily?

You can use the api – DlgDirList(). It will populate the directories or files or drives to your listbox. You can select it by providing appropriate options. See the sample code snippet below, which lists all directories under C:\.

// The path Variable should be modifiable buffer.
// Since DlgDirList() returns data through it.
TCHAR Path[MAX_PATH] = _T("C:\\");
::DlgDirList( GetSafeHwnd(),
              Path, // in/out param.

For identifying directories, the DlgDirList() will decorate the directory name in format “[Directory]”. Now how to get the selected directory path from the listbox? Since its decorated, for that purpose, you can use function – DlgDirSelectEx(). It will undecorated the directory name and returns the real name. See the code snippet below.

// Read the selected directory from Listbox
TCHAR SelectedPath[MAX_PATH] = { 0 };
DlgDirSelectEx( GetSafeHwnd(),
                IDC_LIST1 );

Have a look at similar apis, such as DlgDirListComboBox(), DlgDirListComboBoxEx() etc. The name itself explains about it. Isn’t it? 😉

Targeted Audience – Intermediate.