Wednesday, June 27, 2007

Threads in .NET

Threads in .NET :

A common use of threads is for all kinds of periodical updates.

.NET offers three different ways:


Windows timers with the

System.WinForms.Timer class


Periodical delegate calling with

System.Threading.Timer class


Exact timing with the

System.Timers.Timer class



System.WinForms.Timer class :


For inexact timing we use the window timer. Events raised from the window timer go through the message pump (together with all mouse events and UI update messages) so they are never exact. The simplest way for creating a WinForms.Timer is by adding a Timer control onto a form and creating an event handler using the control's properties. We use the Interval property for setting the number of milliseconds between timer ticks and the Start method to start ticking and Stop to stop ticking.

System.Threading.Timer

class :
The System.Threading.Timer class is a new waiting thread in the thread pool that periodically calls supplied delegates. To use it you must perform several steps:


Create state object which will carry information to the delegate


Create TimerCallback delegate with a method to be called. You can use static or instance methods.


Create a Timer object with time to wait before first call and periods between successive calls (as names of this two parameters suggests, first parameter should be lifetime of this timer object, but it just don't work that way)


Change the Timer object settings with the Change method (same remark on parameters apply)


Kill the Timer object with the Dispose method

System.Timers.Timer

class :

The final timing options come from the System.Timers.Timer class. It represents server-based timer ticks for maximum accuracy. Ticks are generated outside of our process and can be used for watch-dog control. In the same System.Timers namespace you can find the Schedule class which gives you the ability to schedule timer events fired at longer time intervals.

System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.


Create the Timer object. You can a use constructor with interval setting.


Add your event handler (delegate) to the Tick event


Set the Interval property to the desired number of milliseconds (default value is 100 ms)


Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)


Start the ticking with a call to the Start() method, or by setting Enabled property to true.


Stop the ticking with call to the Stop() method or by setting the Enabled property to false.

Tuesday, June 26, 2007

Difference between finalize and dispose

Dispose is a method for realse from the memory for an object.

For eg:

.Dispose.

Finalize is used to fire when the object is going to release the memory.We can set a alert message to says that this object is going to dispose.


For Example if we are opening a file in our application,
this will be released in Dispose() method. Normally before releasing database connection, we have to close the database connection. we have

to place the code for Closing the file operation will be taken place in Finalize() method...

you can close open connections etc before the garbage collector takes over.

This code will be put in Finalize() method. The garbage collector does not close connections when the object gets destroyed.


In general, the Dispose pattern is used to release unmanaged resources in
a timely fashion. This allows you to do this in a deterministic fashion
- in other words, you have control over when they are released. The
Object.Finalize method is also used for the purpose of releasing
resources - but it is non-derministic. You have no control over when it
will be called by the GC. Further, implementing a Finalize method can
have an adverse affect on the performance of the GC because it takes two
passes of the GC to collect objects that override Finalize.

So, in general, if your using objects that manage unmanaged resources,
such as database connections, you implement IDisposable AND override
Finalize. This way, your covered if the client fails to call Dispose -
you know that your resources will then be released when the object is
GC'd. Of course, one you call Dispose - you don't need the finalize
method to be called by the GC and suffer an unnecessary performance
hit... So, generally you'll see the Dispose method implemented sort of
like this:

Public Sub Dispose()
' Do Clean up
System.GC.SupressFinalize(ME)
End Sub

This way, if the client does call dispose, then you don't suffer from
having implemented a Finalize because the object is removed from the
Finalize queue.


when you are writing a class that “owns” relatively scarce resources (such as SQL connections or file handles) which are not managed

by the .NET Common Language Runtime. Both Dispose() and Finalize() return resources by to a system — so if resources are controlled by the

CLR then the .NET automatic Garbage Collection mechanism will take care of the resources and you don’t really need Dispose() or Finalize() in

most situations. A Dispose() method is explicit, meaning you code Dispose() up and explicitly call it in your application or system code. A

Finalize() method is implicit, meaning you code Finalize() up but never actually call it — Finalize() is called behind the scenes by the .NET GC

mechanism. At this point you’ve told the majority of hiring manager what they want to hear. If prompted, you can peel away another layer of detail.

A scare-resource-using class with an explicit Dispose() method inside the class definition must inherit from the IDisposable interface. Typically

such a class will invoke a C# destructor which calls Dispose(), and will invoke the statement GC.SuppressFinalize(this) so that implicit automatic

garbage collection does not interfere with your explicit code. A scare-resource-using class with an explicit Finalize() method inside the class

definition is much more custom, but will usually invoke the statement base.Finalize() to bubble up all Finalize() calls through any inheritance

hierarchy.




Dispose type pattern in C# :
-----------------------------------------

// C#
public class Resource : IDisposable
{
private EmbeddedResource embedded;

public Resource()
{
Console.WriteLine("allocating resource");
embedded = new EmbeddedResource();
}

~Resource()
{
Dispose(false);
}

protected virtual void Dispose(bool disposing)
{
Console.WriteLine("release resource");
if (disposing)
{
embedded.Dispose();
}
}

public void Dispose()
{
Dispose(true);
}
}

Difference between Bitmap and meta files

Difference between Bitmap and meta files :
------------------------------------------------------------
1.Bitmaps are often used for very complex images originating in the real world, such as digitized photographs or video captures.
2.Metafiles are more suitable for human-generated or machine-generated images, such as architectural drawings.

The difference between bitmaps and metafiles is the difference between raster graphics and vector graphics.

1.Raster graphics treats output devices in terms of discrete pixels; ( Bitmap)
vector graphics treats the output device as a Cartesian coordinate system upon which lines and filled objects can be drawn.( Meta

file)

Bitmaps have two major drawbacks.

1.device dependence. For Example : The most obvious device dependency is color. Displaying a color bitmap on a monochrome

device is often unsatisfactory.

2.bitmap often implies a particular resolution and aspect ratio of an image. Although bitmaps can be stretched or compressed, this

process generally involves duplicating or dropping rows or columns of pixels, and this can lead to distortion in the scaled image. A metafile can

be scaled to almost any size without distortion.

3.bitmaps require a large amount of storage space.

Example :bitmap representation of an entire 640-by-480-pixel, 16-color Video Graphics Array (VGA) screen requires more than 150 KB; a

1024-by-768 image with 24 bits per pixel requires more than 2 MB.
Metafiles usually require much less storage space than bitmaps.


One advantage of bitmaps over metafiles, however, is speed.
Copying a bitmap to a video display is usually much faster than rendering a metafile. In recent years, compression techniques have allowed the

shrinking of bitmaps to a size where they can be effectively transmitted over telephone lines and used extensively in World Wide Web pages on

the Internet.

Mastering VC++

Look at the MFC Source in the following site and understand them....

http://www.codeproject.com/useritems/OpenSource_VC_MFC.asp
http://win32assembly.online.fr/tutorials.html

VC++ Win32 Dialog box

VC++ Win32 Dialog box :
-------------------------------------------

Dialog Box :

1.A dialog box generally takes the form of a popup window containing various child window controls.
2.The size and placement of these controls are specified in a "dialog box template" in the program's resource script file. (.rc)

3.window procedure for processing the dialog box messages is referred as the "dialog Procedure."
4.Dialog procedures generally do not process WM_PAINT messages.
5.dialog box can be considered as an input/output "black box" meaning that you don't have to know how a dialog box works internally in order to be able to use it, you only have to know how to interact with it.That's a principle of object oriented programming (OOP) called information hiding.

6.A dialog box is defined as a resource much the same way as a menu. You write a dialog box template describing the characteristics of the dialog box and its controls and then compile the resource script with a resource editor.

7.all resources are put together in the same resource script file.


two main types of dialog box:

1.modal
2.modeless.


Modeless dialog box :
A modeless dialog box lets you change input focus to other window. The example is the Find dialog of MS Word.

Modal dialog box :

two subtypes of modal dialog box:

1.application modal
2.system modal

An application modal dialog box doesn't let you change input focus to other window in the same application but you can change the input focus to the window of OTHER application.
A system modal dialog box doesn't allow you to change input focus to any other window until you respond to it first.

A modeless dialog box is created by calling CreateDialogParam API function.
A modal dialog box is created by calling DialogBoxParam API function.

The only distinction between an application modal dialog box and a system modal one is the DS_SYSMODAL style. If you include DS_SYSMODAL style in a dialog box template, that dialog box will be a system modal one.

Thursday, June 21, 2007

Difference between Panel and GroupBox classes?

Difference between Panel and GroupBox classes?


1.Panel is scrollable and the captions can't be displayed in it



S.No Panel GroupBox
1 Can have scroll bars. Can't have scroll bars.
(Scrollable) (Unscrollable)

2. can't have captions can have captions

Wednesday, June 20, 2007

Marshalling Problem Practically applied

8:22 PM 6/20/2007

Simple DLL Developement :

1. open the simple Win32 DLL project ( TestDll) , it will creates the stdafx.h, stdafx.cpp and TestDll.cpp
2.Add the new header file (TestDll.h)

within the TestDll.h file I added the following code >..

#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif

extern "C"
{
bool DLLDIR GetStatusKeyword();
BOOL DLLDIR GetStatusTypedef();
}

within the TestDll.cpp file, I added the following :

#include "TestDll.h"

bool DLLDIR GetStatusKeyword()
{
return false;
}

BOOL DLLDIR GetStatusTypedef()
{
return false;
}



Select menu items as follows ...

Project ->Settings ->C++ -> General option

Add the DLLDIR_EX macro in the "Preprocessor Definitions " text box.

and then compile it

they will show the EXPORTS keyword in a text box and compile the DLL project.

I got the TestDll.dll and TestDll.lib output files .




Develope the C# client application :

Create the C# Console application and add the namespace "System.Runtime.InteropServices" to it
and add the code as follows :


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace TestDLLClient
{
class Win32API
{
[DllImport("TestDLL.dll")]
public static extern bool GetStatusTypedef();

[DllImport("TestDLL.dll")]
public static extern bool GetStatusKeyword();
}

class Program
{
static void Main(string[] args)
{
if (Win32API.GetStatusKeyword())
{
Console.WriteLine("\n GetStatusKeyword() fn succeeded ");
}
else
{
Console.WriteLine("\n GetStatusKeyword() fn failed ");
}

if (Win32API.GetStatusTypedef())
{
Console.WriteLine("\n GetStatusTypedef() fn Succeeded");
}
else
{
Console.WriteLine("\n GetStatusTypedef() fn failed");
}

Console.Read();
}
}
}


Next Copy the Testdll.dll and Testdll.lib to the "debug" folder of the C# client application.
then compile and run the C# application.

we got the output of the C# application is as follows:


GetStatusKeyword() fn succeeded

GetStatusTypedef() fn failed



Guys the problem is not over,

Next I modified the dll code as follows :


bool DLLDIR GetStatusKeyword()
{

OutputDebugString(" \n GetStatusKeyword() fn ..."); // This will writes the string in debug view...
return false;
}

BOOL DLLDIR GetStatusTypedef()
{
return false;
}



Next Compile the DLL project and copy the TestDll.dll and TestDll.lib to the C# client application's "Debug" folder.


Now Compile the C# application and see the result, u may wonder about the things...

The output is as follows :


GetStatusKeyword() fn failed
GetStatusTypedef() fn failed


It is a funny thing...


Note :
TestDLL application is developed in Visual studio 6.
C# client application is developed in .NET 2005...

Any guys got this problem before or try these things ....

Marshalling Problem :(funny )

Marshalling Problem :

if we are accessing the fn in a VC++ DLL from C# application :

Note the following thing :

1.Within the VC++ DLL fn always make the return type as BOOL instead of bool keyword.

Note :
Try the problem with a simple VC++ DLL contains BOOL as a return type and another fn returns bool data type.

Call it from C# application.


Problems I faced :

bool DLLDIR GetStatus()
{
return false;
}

if I accessed this fn from C# application I got the return value as true.

So try it ...

if it gives the true value then add the OutputDebugString() fn to the GetStatus() fn...
and see what will happen ...( Result : it returns false...)

It is the proposed standard to use BOOL instead of bool , if we access it using interoperability mechanism.

Address Increment with the help of sizeof() operator

int * x = new int[10];
x++; //it will increments the pointer by 2 bytes


char* y = new char[10];
x++; // it will increments the pointer by 1 byte


How pointers are moved during address addition or address subtraction operation ?


they will use sizeof() operator to find the size of it and added it.


For Example

int * x = new int[10];
++x;

can't invoke a non-const member function on a const object

we can't invoke a non-const member function on a const object....


Example :

class CTest
{
public:
CTest() { }
~CTest() { }

void Exam() { }
void Exam2() const { }

};


void f( const CTest testObj)
{
testObj.Exam() ; // Will cause an Error , we are invoking a non-const member function in a const object

}






Invoking a non-const member function on a const object.
Possible solutions
Remove the const from the object declaration.
Add const to the member function.


Example
// C2662.cpp
class C
{
public:
void func1();
void func2() const;
} const c;

int main()
{
c.func1(); // C2662
c.func2(); // no error
}

two input surfaces are same size for (2 In 1Out) DirectX transform filter

DirectX transform filter :
2 In 1 Out ( 2 Inputs and 1 Output )
accepts two inputs and gives one output.

Both the inputs must be the same size ?....

For 2 input directx transform filter,

Both the input surfaces must be the same size.

I tested it with XTL file with XTLTest sample application.


I have given two input video file.

One video file's resolution is 720 * 480 and another one video file's resolution is 320 * 240.

I used my two input directx transform filter.

video filenames and directx transform filter is specified in XTL file.

I run this .XTL file and generated the graph edit file (.grf). I learnt one thing from that Graphedit file.


if the video which is having large size is resized ( using resize filter ) to the another video file's size.

Then both video resolution is same size and then it is passed to the Transition DirectX transform filter (Wipe, DyadicArithmetic)

Tuesday, June 19, 2007

Lvalues and RValues

lvalues and rvalues
----------------------------------

An object is a contiguous region of storage. An lvalue is an expression that refers to such an object. The original

definition of lvalue referred to an object that can appear on the left-hand side of an assignment. However, const

objects are lvalues that cannot be used in the left-hand side of an assignment. Similarly, an expression that can appear

in the right-hand side of an expression (but not in the left-hand side of an expression) is an rvalue. For example


#include

using namespace std;

int& f();

void func()

{

int n;

char buf[3];

n = 5; // n is an lvalue; 5 is an rvalue

buf[0] = 'a'; // buf[0] is an lvalue, 'a' is an rvalue

string s1 = "a", s2 = "b", s3 = "c"; // "a", "b", "c" are rvalues

s1 = // lvalue

s2 +s3; //s2 and s3 are lvalues that are implicitly converted to rvalues

s1 = //lvalue

string("z"); //temporaries are rvalues

int * p = new int; //p is an lvalue; 'new int' is an rvalue

f() = 0; //a function call that returns a reference is an lvalue

s1.size(); //otherwise, a function call is an rvalue expression

}

An lvalue can appear in a context that requires an rvalue; in this case, the lvalue is implicitly converted to an rvalue.

An rvalue cannot be converted to an lvalue. Therefore, it is possible to use every lvalue expression in the example as an rvalue, but not vice versa.

Sunday, June 17, 2007

I implemented the StrConcat() fn in a VC++(unmanaged) DLL..


VC++ DLL code contains :



void StrConcat( char *pszSource, char* pszDest )

{

strcat(pszDest, pszSource); //copy the string

}



here is my new code ...we think it looks silly programming...


ok ...


pszSource and pszDest are arguments to the StrConcat( ) fn( Great Invention).


Important Points :

1.pszSource acts as a input parameter to StrConcat() fn.

2.pszDest acts as both input and output parameter to StrConcat() fn.


I need to call this method from C# application. we can make use of the .NET's platform invocation services to call the DLL fn in C#.


Platform Invocation Services :

-------------------------------------

1.Platform Invocation Services (PInvoke) allows managed code to call unmanaged functions that are implemented in a DLL.


Unmanaged code called in managed code through marshalling.


Calling a DLL Export Directly from C#

To declare a method as having an implementation from a DLL export, do the following:

1.Declare the method with the static and extern C# keywords

2.Attach the DllImport attribute to the method. The DllImport attribute allows you to specify the name of the DLL that contains the method. The common practice is to name the C# method the same as the exported method, but you can also use a different name for the C# method.

3.Optionally, specify custom marshaling information for the method's parameters and return value, which will override the .NET Framework default marshaling.

C# application :



class PlatformInvokeTest

{

[DllImport("CustomDLL.dll")]

public static extern void StrConcat(string source, string dest); // this is the C++ function //exposed by the dll

}

Did u think the above will concatenate the string ... I am sure we will not get the concatenated string in dest.



The reason is as follows :

I already told the Unmanaged code DLL is called through the marshalling mechanism.

for Marshalling, we have to specify whether In or Out parameter passed to the fn. if we are not specifying anything in dest string. we have to declare it as

follows :

[DllImport("CustomDLL.dll")]

public static extern void StrConcat(string source, ref string dest); // this is the C++ function exposed by the dll

we can specify the input parameter using In attribute.

we can specify the output parameter usign Out attribute.



if the parameter is both in and out parameter, At that time we have to use ref keyword to indicate the pass by reference.

Instead of it, we can use

[DllImport("CustomDLL.dll")]

public static extern void StrConcat(string source, StringBuilder dest); // this is the C++ function exposed by the dll

//StringBuilder class has both In and out attribute by default .

two types of Marshalling :

1.Default Marshalling

2.Custom marshalling

Default Marshaling and Specifying Custom Marshaling for Parameters to Unmanaged Methods

When calling an unmanaged function from C# code, the common language runtime must marshal the parameters and return values.

For every .NET Framework type there is a default unmanaged type, which the common language runtime will use to marshal data across a managed to unmanaged function call. For example, the default marshaling for C# string values is to the type LPTSTR (pointer to TCHAR char buffer). You can override the default marshaling using the MarshalAs attribute in the C# declaration of the unmanaged function.





About Example :

Next we have to call the VC++ function puts() from msvcrt.dll. this will displays the characters on screen .

Example for custom marshalling :

// Marshal.cs

using System;

using System.Runtime.InteropServices;



class PlatformInvokeTest

{

[DllImport("msvcrt.dll")]

public static extern int puts(

[MarshalAs(UnmanagedType.LPStr)]

string m);

[DllImport("msvcrt.dll")]

internal static extern int _flushall();





public static void Main()

{

puts("Hello World!");

_flushall();

}

}

string is marshalled as LPSTR data type in VC++. // [MarshalAs(UnmanagedType.LPStr)]

Specifying Custom Marshaling for User-Defined Structs

You can specify custom marshaling attributes for fields of structs and classes passed to or from unmanaged functions. You do this by adding MarshalAs attributes to the fields of the struct or class. or we can use the StructLayout Attribute.

[StructLayout(LayoutKind.Sequential)]

public class LOGFONT

{

public const int LF_FACESIZE = 32;

public int lfHeight;

}

Callback function in VC++ DLL is converted as delegate in C# :



if the VC++ DLL have the Call back fn in a DLL as follows :

typedef void (__stdcall *PFN_MYCALLBACK)();

int __stdcall MyFunction(PFN_ MYCALLBACK callback);

we can call it through the delegate keyword.

How can we call the above fn in C# ?

To call MyFunction from managed code, declare the delegate, attach DllImport to the function declaration, and optionally marshal any parameters or the return value:

public delegate void MyCallback();

[DllImport("MYDLL.DLL")]

public static extern void MyFunction(MyCallback callback);





Summary :

1.we can call the Unmanaged DLL fn using DllImport attribute.

2.For every .NET Framework type there is a default unmanaged type, which the common language runtime will use to marshal data across a managed to unmanaged function call.

3.the default marshaling for C# string values is to the type LPTSTR (pointer to TCHAR char buffer). You can override the default marshaling using the MarshalAs attribute in the C# declaration of the unmanaged function.

4.we can do Custom Marshaling for User-Defined Structs using MarshalAs or StructLayout attribute.

5. Callback fn in unmanaged code(VC++ DLL) called with delegate in C#.( Managed code )










Saturday, June 16, 2007

DirectX transform is also a BHO ( Browser helper Object)

DirectX transform Filters implement the IObjectwithSite interface So it is called as Browser Helper Object.

Browser Helper Object (BHO) is a DLL module designed as a plugin for Microsoft's Internet Explorer web browser to provide added functionality. BHOs were introduced in October 1997 with the release of version 4 of Internet Explorer. Most BHOs are loaded once by each new instance of Internet Explorer. However, in the case of the Windows File Explorer, a new instance is launched for each window.

Some modules enable the display of different file formats not ordinarily interpretable by the browser. The Adobe Acrobat plugin that allows Internet Explorer users to read PDF files within their browser is a BHO.

Other modules add toolbars to Internet Explorer, such as the Alexa Toolbar that provides a list of web sites related to the one you are currently browsing, or the Google Toolbar that adds a toolbar with a Google search box to the browser user interface.

Browser Helper Objects

When an instance of Internet Explorer 4.0 is started, it looks in the registry for CLSIDs stored under the following key:
HKLM\SOFTWARE\Microsoft\Windows \CurrentVersion\Explorer\Browser Helper Objects
If this key exists and there are CLSIDs listed under it, Internet Explorer will use CoCreateInstance() to try to create an instance of each object listed as a subkey under this key. Note that the CLSID of the object you create must be listed as a subkey and not a named value.

For example, imagine that the following entry exists in the registry, HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects\{CE7C3CF0-4B15-11D1-ABED-709549C10000}. Internet Explorer will try to create an instance of the object pointed to by the CLSID {CE7C3CF0-4B15- 11D1-ABED-709549C10000} each time Internet Explorer starts.

These registry keys can be created manually or through the self registration portion of your COM application.

There are some requirements when creating a Browser Helper Object

• The application that you create must be an in-proc server (that is, DLL).
• This DLL must implement IObjectWithSite.
• The IObjectWithSite::SetSite() method must be implemented. It is through this method that your application receives a pointer to Internet Explorer's IUnknown. (Internet Explorer actually passes a pointer to IWebBrowser2 but the implementation of SetSite() receives a pointer to IUnknown.) You can use this IUnknown pointer to automate Internet Explorer or to sink events from Internet Explorer.
• It must be registered as a Browser Helper Object as described above.
WARNING: Internet Explorer will create an instance of each Browser Helper Object listed in the registry every time a new instance of Internet Explorer is started. This means that if you have Active Desktop installed, the Browser Helper Objects will be loaded every time you open a new folder as well as when the browser itself is started.

Thursday, June 14, 2007

mutable keyword

mutable keyword :
-----------------------
Class member functions may be declared as const, which causes this to be treated as a
const pointer. Thus, that function cannot modify the object that invokes it. Also, a const
object may not invoke a non-const member function. However, a const member
function can be called by either const or non-const objects.

within const member fns we can' change the value. In C++ we can change the value using mutable keyword.

class X
{
int i;
public:
int f1() const; // const member function
};


int X::f1() const
{

i = 10; // This will gives error because we are trying to modify the value in a const member function

return i;
}

we can modify the values if we use the mutable keyword. Following code will works...

This is the concept of mutable in C++.



class X
{
mutable int i;
public:
int f1() const; // const member function
};


int X::f1() const
{

i = 10; // This will gives error because we are trying to modify the value in a const member function

return i;
}

Tuesday, June 12, 2007

Real use of BitFields

Bit-Fields


C/C++ has a built-in feature called a bit-field
that allows you to access a single bit. Bit-fields can be useful for a number of reasons,
such as:
1. If storage is limited, you can store several Boolean (true/false) variables in
one byte.
2. Certain devices transmit status information encoded into one or more bits
within a byte.
3.Certain encryption routines need to access the bits within a byte.


To access individual bits, C/C++ uses a method based on the structure.
The general form of a bit-field definition is

struct struct-type-name {
type name1 : length;
type name2 : length;
..
.
type nameN : length;
} variable_list;

Here, type is the type of the bit-field and length is the number of bits in the field.
A bit-field must be declared as an integral or enumeration type. Bit-fields of length
1 should be declared as unsigned, because a single bit cannot have a sign.
Bit-fields are frequently used when analyzing input from a hardware device.
For example, the status port of a serial communications adapter might return a
status byte organized like this:


Bit Meaning When Set
0 Change in clear-to-send line
1 Change in data-set-ready
2 Trailing edge detected
3 Change in receive line
4 Clear-to-send
5 Data-set-ready
6 Telephone ringing
7 Received signal


You can represent the information in a status byte using the following bit-field:


struct status_type {
unsigned delta_cts: 1;
unsigned delta_dsr: 1;
unsigned tr_edge: 1;
unsigned delta_rec: 1;
unsigned cts: 1;
unsigned dsr: 1;
unsigned ring: 1;
unsigned rec_line: 1;
} status;
You might use a routine similar to that shown here to enable a program to determine
when it can send or receive data.


status = get_port_status();
if(status.cts) printf("clear to send");
if(status.dsr) printf("data ready");


To assign a value to a bit-field, simply use the form you would use for any other type
of structure element. For example, this code fragment clears the ring field:

status.ring = 0;

How to call Unmanaged DLL from C# application ?

How to call Unmanaged DLL from C# application ?



I develeoped the win32 DLL.

I added the code in the DLL header file as follows :



#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif

extern "C"
{
bool DLLDIR GetSysInfo(char* pszSystemName);

};



DLL implementation file I added its defn


How I accessed the DLL in C# ?


VC++ DLL is an Unmanaged code.


This is following way How I accessed that file...


I just copied the .DLL and .LIB files from my DLL project.


and copied it to the debug folder of the C# application


Within C# application



using System.Runtime.InteropServices; // For Interoperability

[DllImport("RemoteSystemDLL.dll")]
public static extern bool GetSysInfo(StringBuilder buf);

and called this GetSysInfo() fn in my application.

// this is the C++ function exposed by the dll

Monday, June 11, 2007

Operator Keywords

ANSI C++ introduced the operator keywords :

C++ suggested to use the following key words for any operation.

operator operator Keywords Description

&& and logical AND

|| or logical OR

! not logical NOT

!= not_eq Inequality

& bitand bitwise and

| bitor bitwise or

^ xor bitwise xor

~ compl complement operator

&= and_eq bitwise AND assignement

|= or_eq bitwise OR assignement

^= xor_eq bitwise XOR assignement



Example program :
=================

The following example program is compiled in microsoft visual C++
win32 console application.


#include

int main(int argc, char* argv[])
{

int i = 0;
int j = 20;
printf("Hello World! : %d", i and j);
return 0;
}


Note the program, I used the "and" operator keyword. In that way we can access the

operators listed above.

Combo box problem

Scenario :
---------------
I added the combo box in a dialog box by using the resource editor.

Next I am using

SendMessage(hwnd,CB_ADDSTRING,0,"Sundar");

or

SendDlgItemMessage(dlgHwnd,IDC_combo,CB_ADDSTRING,0,"Sundar");


Both the SendMessage() function is not working. the combo box style is a drop down. I am not able to identify the cause of the problem.


Solution Attempts:
-------------------------
1. If I am creating the combo box dynamically in a dialog box,the above code is working.( string is added to the

combo box.

2. So I checked the style and properties of the combo box. I changed the style as dropdown list. But it is also not working.



Solution : I got the solution from the google groups.

the answer might be very silly...

change the vertical size in Combo Box, then it will works fine.

Solution Reason :


During design time the width and height is determined based on the control size. Here the problem lies...

The Height of the combo box is both the edit control and the drop down list .

literally combo box is nothing but a combination of edit box(static for Drop down list) and list box .

the height is for both the edit control and list box control. Actually during design time, the height is allocated only for the

edit control. So there is no size left for displaying the items in a drop down list.


1. I changed the width and height of the combo box in a .rc ( resource script file) look at the format of the controls in .rc file


For EDITTEXT, SCROLLBAR, LISTBOX, and COMBOBOX, the format is

control-type id, xPos, yPos, xWidth, yHeight, iStyle




2.So in the dynamically created Combo box also this will be true ???

Check whether this problem also be arised to dynamically created combo box ?

yes I got the same problem in dynamically created control also...


The following code have x,y,width,height in sequence as 100,100,200,10.

the height is 10... So there is no place for displaying the drop down list box.



hwndCombo = CreateWindow("combobox","sundar",CBS_DROPDOWNLIST | WS_CHILD | WS_TABSTOP,100,100,200,10,hWnd,NULL,hInstance,NULL);

if I changed the height as 100 then it displays the drop down list box look at the following code it works well.


hwndCombo = CreateWindow("combobox","sundar",CBS_DROPDOWNLIST | WS_CHILD | WS_TABSTOP,100,100,200,100,hWnd,NULL,hInstance,NULL);





Learnt things from this problem :

Combo Box styles :

3 types of combo box

1.Simple ( displays the edit control and list box control )
2.Dropdown ( edit control with list box but the listbox is displayed only when drop down button is clicked )
3. Drop Down list ( static control with list box, we can't enter data into the static control )


Difference Between CB_ADDSTRING and CB_INSERTSTRING :
-----------------------------------------------------------------------------

1. CB_ADDSTRING adds the data in a sorted order

For Example

SendMessage(hwndCombo, CB_ADDSTRING,0, "Sundar");
SendMessage(hwndCombo, CB_ADDSTRING,0, "Arun");

The items are displayed in the combo box in the following order :

Arun
Sundar

2.In case of CB_INSERTSTRING will not add data in a sorted order


SendMessage(hwnCombo, CB_INSERTSTRING, -1 // Add data at the end of the combo box
"sundar");

SendMessage(hwndCombo, CB_INSERTSTRING, -1, // adds data at the end of the combo box

"arun");

The items are displayed in the combo box in the following order :
sundar
arun



Test the ATL based SendMessage :
------------------------------------------------

win32 Dialog based application structure:

WinMain() fn has DialogBox() method to create the dialog box.


define IDD_DIALOG 101
#define IDC_COMBO 201
/* end combobox.h */
/* begin combobox.rc */

#include "winresrc.h"
#include "combobox.h"


IDD_DIALOG DIALOG DISCARDABLE 0, 0, 186, 95
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Dialog"
FONT 8, "MS Sans Serif"
BEGIN
DEFPUSHBUTTON "OK",IDOK,129,7,50,14
PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14
COMBOBOX IDC_COMBO,17,16,101,65,CBS_DROPDOWN |
WS_VSCROLL | WS_TABSTOP
END
/* end combobox.rc */
/* begin combobox.c */


#include "windows.h"
#include
#include "combobox.h"

BOOL CALLBACK DlgProc(HWND hw, UINT msg, WPARAM wp, LPARAM lp)
{
HWND combo = 0;
int cursel = 0;
char before[100] = {0};
char after [100] = {0};
char results[sizeof before + sizeof after] = {0};
switch(msg)
{
case WM_INITDIALOG:
combo = GetDlgItem(hw, IDC_COMBO);
SendMessage(combo, CB_ADDSTRING, 0, (LPARAM)"one");
SendMessage(combo, CB_ADDSTRING, 0, (LPARAM)"two");
SendMessage(combo, CB_ADDSTRING, 0, (LPARAM)"three");
return TRUE;
case WM_COMMAND:
switch(LOWORD (wp))
{
case IDOK:
case IDCANCEL:

EndDialog(hw, 0);
return TRUE;

case IDC_COMBO:
if(HIWORD(wp) == CBN_SELCHANGE)
{
SendMessage((HWND)lp, WM_GETTEXT, sizeof before,
(LPARAM)before);
cursel = SendMessage((HWND)lp, CB_GETCURSEL, 0, 0);
SendMessage((HWND)lp, CB_GETLBTEXT, cursel, (LPARAM)after);
sprintf(results, "before: %s\nafter: %s", before, after);
MessageBox(hw, results, "", MB_OK);
}
return TRUE;
}
}
return 0;
}


int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), 0, DlgProc);
return 0;
}

/* end combobox.c */




Some more try :


CWindow myWindow;
myWindow.Attach(hWndFoo);
myWindow.SendMessage(WM_PAINT,0L,0L);


Within ATL based component , I used the following code :


::SendDlgItemMessage(m_hWnd,IDC_cboReplacementForRed, CB_SETCURSEL,(WPARAM)GetCurrentSelection (m_ShiftChannelsParams.replacementForRed),0);


I changed it as ATL based window class as follows , it is also working well.


HWND hwndForRed;
hwndForRed = GetDlgItem(IDC_cboReplacementForRed);

CWindow wndForRed;
wndForRed.Attach(hwndForRed);
wndForRed.SendMessage(CB_SETCURSEL,(WPARAM)GetCurrentSelection(m_ShiftChannelsParams.replacementForRed),0);



I modified the above code as follows :

HWND hwndForRed;
hwndForRed = GetDlgItem(IDC_cboReplacementForRed);
CWindow wndForRed(hwndForRed);
wndForRed.SendMessage(CB_SETCURSEL,(WPARAM)GetCurrentSelection(m_ShiftChannelsParams.replacementForRed),0);


if we are using Attach() method we must call Detach() method inorder to remove the hwnd from CWindow.
Ideas :
------------


If we got any error in the GUI controls, then check the net for the source code...

if they have some width and height, then use it in ur program also... this is the simple way to solve the problem.

( But not a knowledge based way...) this can be done when we want quick results.

Friday, June 08, 2007

__FILE__, __LINE__ and __cplusplus macro

we often meet the __FILE__ macro in an MFC application. it seems MFC macro.But it is one of the c++ predefined macro. __FILE__ macro is available in C++ . __LINE__ macro is also available in C++.


__FILE__ & __LINE__ macros specified in C & C++ standards are useful to provide some debugging information, during run-time. During pre-processing stage of compilation,

__FILE__ macro expands to the name of the file being compiled, in the form of a C string constant;
__LINE__ expands to the line number of the source file that is being compiled, in the form of an integer constant.




Simple Example with them :
-----------------------------------

Filename is "C:\MacroTesting.cpp"
-------------------------------------------

#include
#include

int main(int argc, char **argv)
{
FILE *fd;

char errinfo[100];

fd = fopen ("C:\Test.txt" , "r");
if (fd == NULL)
{
sprintf (errinfo, "Error at line %d of %s", (__LINE__ - 3), __FILE__);
perror (errinfo);
free (errinfo);
}
else
{
printf ("file descriptor = %d", fileno(fd));
fclose (fd);
}

return (0);
}



In the above program we are opening "C:\test.txt" in read mode.

if the file is not available, then it will displays error as follows :

Output :

Error at line 14 of C:\MacroTesting.cpp

This will be very useful for identifying errors in an application ( if the application has so many files at that time it will be very

useful to identify where the program failed...)





__cpluscplus macro C++
----------------------------------


#ifdef __cplusplus
extern "C" {
#endif

DECLARE_INTERFACE_(IHistogram, IUnknown)
{

STDMETHOD(GetParams) (THIS_ HistogramParams *irp ) PURE;

};

#ifdef __cplusplus
}
#endif

Thursday, June 07, 2007

constant qualifier testing

Const qualifier test application

#include
void ConstTesting()
{
char* const ptr1 = "Good"; //address is constant
char* s = "sundar";
ptr1 = s; //will be in an error because address is constant


int m = 10;
int const *ptr2 = &m; //content is constant
*ptr2 = *ptr2 + 2; //the content is constant so this will gives error



const char* const cp = "xyz"; //Both address and content is constant

cp = s; //address is constant so this will gives me error

strcpy(cp,"sundar"); //content is constant so this will also gives error







}

int main(int argc, char* argv[])
{
ConstTesting();
return 0;
}

cpp tips

various usage of const keyword with variable:


1.char* const ptr1 ="Good";

2.int const *ptr2 = &m ; //content is constant

3.const char* const cp = "xyz" ; //Both address and content is constant



can u differentiate the above three usage ?

...

Ans :

1.char* const ptr1 ="Good"; //address is constant

2.int const *ptr2 = &m ; //content is constant

3.const char* const cp = "xyz" ; //Both address and content is constant


Is there any difference between new() and malloc() ?

new operator advantages than malloc :

1.new operator will automatically computes the size of the object.

No need to use sizeof() operator.

2.It automatically returns the correct pointer type. So there is no need to use a type cast.

3.It is possible to initialize the object while creating the memory space.

4. like any other operator, new operator can be overloaded.

Wednesday, June 06, 2007

Inpirational words

I could only convey one thought that would help you to be more successful, I would tell you to “write down your goals, make plans to achieve them, and work on your plans every single day.”

DirectX transform filters working mechanism

How the DirectX transform filters work ?
1.using XTL Test we can create the .grf file(graphedit)
2. From that .grf file, what I learned ?...

The Source is decompressed and then given to the DEX Filter( XML Rendering engine or DirectXEditing Filter) .

3.DirectX transform wrapper acts like a callback (sample grabber filter). DEX filter samples the frames and passed it

to the DirectX transform wrapper. This Directx transform wrapper( it can be any effect filter) processes and modifies the frame.

Next the Processed frame is passed to the DEX Filter and DEX filter renders the frames using video renderer.


The users specify the output width and height in the .XTL file. based on it the resizer filter is added. if the output video width and height is not

specified, the input video width and height is taken as an output video width and height.( Both the cases the resizer will be added to the graph)

Through XTL file, we can change the frame rate of the video

highway.avi -> AVI Splitter -> AVI Decompressor ->Resizer-> Frame Rate converter -> DEX Filter 000A---Out0--> DEXER queue -> DEX video renderer



Frame rate Converter --------> In 2 of DEX Filter --Out 0--> DEXER queue


DXT Wrapper ---->In 3 of DEX filter ...

Out 0 of DEX Filter -> Input of DXT wrapper

Out 0 of DEX filter is connected to the input pin of the DXT wrapper.

Tuesday, June 05, 2007

Name mangling

Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. The compiler generates function names with an encoding of the types of the function arguments when the module is compiled. Name mangling is commonly used to facilitate the overloading feature and visibility within different scopes. Name mangling also applies to variable names. If a variable is in a namespace, the name of the namespace is mangled into the variable name so that the same variable name can exist in more than one namespace. The C++ compiler also mangles C variable names to identify the namespace in which the C variable resides.

The scheme for producing a mangled name differs with the object model used to compile the source code: the mangled name of an object of a class compiled using one object model will be different from that of an object of the same class compiled using a different object model. The object model is controlled by compiler option or by pragma.

Name mangling is not desirable when linking C modules with libraries or object files compiled with a C++ compiler. To prevent the C++ compiler from mangling the name of a function, you can apply the extern "C" linkage specifier to the declaration or declarations, as shown in the following example:

extern "C" {
int f1(int);
int f2(int);
int f3(int);
};

This declaration tells the compiler that references to the functions f1, f2, and f3 should not be mangled.

The extern "C" linkage specifier can also be used to prevent mangling of functions that are defined in C++ so that they can be called from C. For example,

extern "C" {
void p(int){
/* not mangled */
}
};

name mangling is used in storing information about classes,templates,namespaces and operator overloading.
this means that object code produced by different compilers is not usually linkable.

Look more about name mangling :

http://en.wikipedia.org/wiki/Name_mangling

Different Style of Const in a fn

const char* GetOutputData()
{
// within this fn, we can change any values of a variable inside this fn
// and returns constant pointer, we can't modify the pointer returned by this fn
}


char* GetOutputData() const
{
//this fn will not change any values of a variable inside this fn
// and returns char* pointer, we can modify the pointer returned by this fn
}

const char* GetOutputData() const
{
//this fn will not change any values of a variable inside this fn
// and returns constant pointer, we can't modify the pointer returned by this fn

}

Rotation filter

Rotation filter...:


private void RotationMenu_Click(object sender, System.EventArgs e)
{
Graphics g = this.CreateGraphics();
g.Clear(this.BackColor);
Bitmap curBitmap = new Bitmap(@"roses.jpg");
g.DrawImage(curBitmap, 0, 0, 200, 200);
// Create a Matrix object, call its Rotate method,
// and set it as Graphics.Transform
Matrix X = new Matrix();
X.Rotate(30);
g.Transform = X;
// Draw image
g.DrawImage(curBitmap,
new Rectangle(205, 0, 200, 200),
0, 0, curBitmap.Width,
curBitmap.Height,
GraphicsUnit.Pixel) ;
// Dispose of objects
curBitmap.Dispose();
g.Dispose();
}


private void Rotate_Click(object sender,
System.EventArgs e)
{
// Create a Graphics object
Graphics g = this.CreateGraphics();
g.Clear(this.BackColor);
// Create a Matrix object
Matrix X = new Matrix();
// Rotate by 45 degrees
X.Rotate(45, MatrixOrder.Append);
// Apply Matrix object to the Graphics object
// (i.e., to all the graphics items
// drawn on the Graphics object)
g.Transform = X;
// Draw a line
g.DrawLine(new Pen(Color.Green, 3),
new Point(120, 50),
new Point(200, 50));
// Fill a rectangle
g.FillRectangle(Brushes.Blue,
200, 100, 100, 60);
// Dispose of object
g.Dispose();
}

Monday, June 04, 2007

sample applications for Pointer to derived types and pointer to member

#include
class CConstructorThrow
{
public:
CConstructorThrow();
~CConstructorThrow();
};

CConstructorThrow::CConstructorThrow()
{
try
{
throw 100;
}
catch(...)
{
printf("\n Exception in CConstructorThrow::CConstructorThrow()...");
}

}
CConstructorThrow::~CConstructorThrow()
{

}

int main(int argc, char* argv[])
{
CConstructorThrow* pThrow = new CConstructorThrow();

if(pThrow == NULL)
{
printf("\n Constructor throw returned the null pointer ");

}
else
{
printf("constructor throw returned the valid pointer");
}
return 0;
}


I got the output as :

Exception in CConstructorThrow::CConstructorThrow()...
constructor throw returned the valid pointer








Example 2 :

Normally we

#include
#include
using namespace std;

void nothrowTesting()
{
int *p;

p = new(nothrow) int[20];

if( p == NULL)
{
printf("\n Memory allocation is failed...");
return;
}
else
{
printf("\n Memory Allocation is succeeded...");
}



if(p)
{
delete [] p;
p = NULL;
}
}


int main(int argc, char* argv[])
{
nothrowTesting();
return 0;
}


Example 3 :
-------------------------




#include
#include
using namespace std;
class nothrowClass
{
public:
nothrowClass() ;
~nothrowClass();


};

nothrowClass::nothrowClass()
{
printf("\n constructor..");
throw 100;
}

nothrowClass::~nothrowClass()
{
printf("\n destructor..");

}

void nothrowTestingClient()
{
nothrowClass* pClass;

try
{

pClass = new nothrowClass();

if(pClass == NULL)
{
printf("\n Invalid Pointer");

}
else
{

printf("\n valid Pointer");

if(pClass)
{
delete pClass;
pClass = NULL;
}


}
}
catch(...)
{
printf("\n Error in Allocation..");
}
}

int main(int argc, char* argv[])
{
nothrowTestingClient();
return 0;
}


output :
-----------
constructor
Error in Allocation (exception)
if the exception occurs the normal flow of program will be affected... So How can we handle this situation ?...

Example 4:
-------------------

#include

class Base
{
public:
Base()
{

}
~Base()
{

}

void DisplayBase()
{
printf("\n Base Display");
}


};

class Derived: public Base
{
public:
Derived()
{
}

~Derived()
{
}
void DisplayDerived()
{
printf("\n Derived Display");
}


};


int main(int argc, char* argv[])
{
Derived d;
Base* bp;

bp = &d; // we r typecasting the derived class to base class
bp->DisplayBase();

//bp->DisplayDerived() fn is an error we have to call like this...

((Derived*)bp)->DisplayDerived(); //This is the use of typecasting
return 0;
}


Example 5:
---------------------

#include

// .* and ->* are pointer to member operators

class PointerToMember
{
public:

int (PointerToMember::*fn)();

int (PointerToMember::*fn2)();

PointerToMember(int i)
{
val = i;
fn = double_val;
fn2 = double_val;

}


int val;
int double_val() { return val+val; }


int callPointer()
{
return (this->*fn)();
}





};

int main(int argc, char* argv[])
{


PointerToMember p(1); //Initialize the constructor of the class

printf("\n fn return value is : %d",p.callPointer());


return 0;
}

sample applications for Pointer to derived types and pointer to member

#include
class CConstructorThrow
{
public:
CConstructorThrow();
~CConstructorThrow();
};

CConstructorThrow::CConstructorThrow()
{
try
{
throw 100;
}
catch(...)
{
printf("\n Exception in CConstructorThrow::CConstructorThrow()...");
}

}
CConstructorThrow::~CConstructorThrow()
{

}

int main(int argc, char* argv[])
{
CConstructorThrow* pThrow = new CConstructorThrow();

if(pThrow == NULL)
{
printf("\n Constructor throw returned the null pointer ");

}
else
{
printf("constructor throw returned the valid pointer");
}
return 0;
}


I got the output as :

Exception in CConstructorThrow::CConstructorThrow()...
constructor throw returned the valid pointer








Example 2 :

Normally we

#include
#include
using namespace std;

void nothrowTesting()
{
int *p;

p = new(nothrow) int[20];

if( p == NULL)
{
printf("\n Memory allocation is failed...");
return;
}
else
{
printf("\n Memory Allocation is succeeded...");
}



if(p)
{
delete [] p;
p = NULL;
}
}


int main(int argc, char* argv[])
{
nothrowTesting();
return 0;
}


Example 3 :
-------------------------




#include
#include
using namespace std;
class nothrowClass
{
public:
nothrowClass() ;
~nothrowClass();


};

nothrowClass::nothrowClass()
{
printf("\n constructor..");
throw 100;
}

nothrowClass::~nothrowClass()
{
printf("\n destructor..");

}

void nothrowTestingClient()
{
nothrowClass* pClass;

try
{

pClass = new nothrowClass();

if(pClass == NULL)
{
printf("\n Invalid Pointer");

}
else
{

printf("\n valid Pointer");

if(pClass)
{
delete pClass;
pClass = NULL;
}


}
}
catch(...)
{
printf("\n Error in Allocation..");
}
}

int main(int argc, char* argv[])
{
nothrowTestingClient();
return 0;
}


output :
-----------
constructor
Error in Allocation (exception)
if the exception occurs the normal flow of program will be affected... So How can we handle this situation ?...

Example 4:
-------------------

#include

class Base
{
public:
Base()
{

}
~Base()
{

}

void DisplayBase()
{
printf("\n Base Display");
}


};

class Derived: public Base
{
public:
Derived()
{
}

~Derived()
{
}
void DisplayDerived()
{
printf("\n Derived Display");
}


};


int main(int argc, char* argv[])
{
Derived d;
Base* bp;

bp = &d; // we r typecasting the derived class to base class
bp->DisplayBase();

//bp->DisplayDerived() fn is an error we have to call like this...

((Derived*)bp)->DisplayDerived(); //This is the use of typecasting
return 0;
}


Example 5:
---------------------

#include

// .* and ->* are pointer to member operators

class PointerToMember
{
public:

int (PointerToMember::*fn)();

int (PointerToMember::*fn2)();

PointerToMember(int i)
{
val = i;
fn = double_val;
fn2 = double_val;

}


int val;
int double_val() { return val+val; }


int callPointer()
{
return (this->*fn)();
}





};

int main(int argc, char* argv[])
{


PointerToMember p(1); //Initialize the constructor of the class

printf("\n fn return value is : %d",p.callPointer());


return 0;
}

Sunday, June 03, 2007

Object conversion

#include "stdio.h"
class ObjectConversion
{
public:
ObjectConversion() { }
~ObjectConversion(){ }

operator int() { return 10; }
operator double(){ return 12.002; }

};

void ObjectConversionClient()
{
ObjectConversion obj;
int i ;
double d;

i = obj;
d = obj;

printf("\n value of i is %d",i);
printf("\n value of d is %lf",d);
}
int main(int argc, char* argv[])
{
ObjectConversionClient();
return 0;
}


The output for this program is :

value of i is 10
value of d is 12.00200

Cpp Exceptions

Exceptions :
1.

The following code will catch the exception:

try
{
throw 100;
}
catch(int i)
{
printf(“\n Exception :%d”, i );
}


Exception :
Exception Testing () fn didn’t handle the exception then it will throws the exeption to the called function.


void ExceptionTesting()
{
throw 100;
}

int main(int argc, char* argv[])
{
try
{
ExceptionTesting();
}
catch(int i)
{
printf("\n main() fn exception : %d",i);

}
return 0;
}

Catching class types:
We can also create our own exceptions.

//Catching class type exceptions
#include
#include

class MyException
{
public:


MyException() { }

~MyException(){ }


};

int main(int argc, char* argv[])
{
int i = 0;

try
{
if(i == 0)
{
throw MyException();
}
}
catch(MyException e)
{
printf("\n Base classException");
}

return 0;
}
Catching Derived class Exception:

We can catch the derived class using the base class .

//Catching class type exceptions
#include
#include
class MyException
{
public:
MyException() { }
~MyException(){ }
};

class Derived:public MyException
{
public:
Derived(){ }
~Derived(){ }
};
int main(int argc, char* argv[])
{
int i = 0;

try
{
if(i == 0)
{
throw Derived();
}
}
catch(MyException e)
{
printf("\n Base classException");
}
catch(Derived d)
{
printf("\n Derived class Excption");
}

return 0;
}


Even though we passed the derived class exception, the base class will catch the “Base class Exception”.

Warning C4286: 'class Derived' : is caught by base class ('class MyException')