சனி, 20 பிப்ரவரி, 2010

VC++ tips:

VC++ tips:


1) Explain COM?
1. How do I get the main window Handle?

AfxGetMainWnd() API returns the main wnd handle for you. You can get whatever you want on the main window. Here I give some piece of code

AfxGetMainWnd()->GetDlgItemText(IDC_EDIT_TEST1, str);
SetDlgItemText(IDC_EDIT_TEST1, str);


2.Can I have same ID for the control in different dialog?

Sure. There is no problem when you are assigning same ID for the controls in different dialog. But in the same dialog, we can’t able to create two controls with the same ID.
For example, if u has two dialogs with one edit control for each, then you will enter same ID as IDC_EDIT_TEST1 for the two edit controls. Surprisingly, it will work so nice. Reason for this is each control is coupled with theirs own window.


3. How do I convert CString to WCHAR?
Steps here,
WCHAR wFile = new WCHAR[MAX_PATH];
mbstowcs(wFile, string.GetBuffer(), string.GetLength() + 1);

now the wfile has the string in wchar format.

4. How can I draw image using OpenCV in a simple way?

Easiest way to draw an image on the DC is OpenCV with GDI+. GDI+ reduces our task to copy the image data from Iplimage. Here some code for ur reference.

CString sFileName("");
int iWidth, iHeight;
CRect rect;
IplImage *SU_Image = 0;
iWidth = iHeight = 0;
char m_chBmpBuf[2048];

M_StPict.GetClientRect(&rect);
iWidth = rect.Width(); iHeight = rect.Height();

IplImage *img=cvLoadImage(sFileName.GetBuffer(sFileName.GetLength()),3);

if(!img) return;

SU_Image = cvCreateImage(cvSize(iWidth,iHeight),8,3);
cvResize(img, SU_Image);

Bitmap bmp(iWidth,iHeight,iWidth*3, PixelFormat24bppRGB, (BYTE*)SU_Image->imageData);

Graphics gr(M_StPict.GetDC()->m_hDC);
gr.DrawImage(&bmp, 0, 0, iWidth, iHeight);

cvReleaseImage(&SU_Image);
cvReleaseImage(&img);


5. What is the difference between public, private, and protected?
• A member (either data member or member function) declared in a private section of a class can only be accessed by member functions and friends of that class
• A member (either data member or member function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes
• A member (either data member or member function) declared in a public section of a class can be accessed by anyone
6. What is Copy Constructor?
CPoint pt(1,2);
CPoint pt1( pt ); //copy constructor
CPoint pt2 = pt1; //copy constructor

In the copy constructor, the compiler creates a new object pt2 and copies the data from pt1 member-by-member, into pt2.

7. Not possible this kind of inclusion.

If I have two file namely A & B. The A file includes the B file and B file includes A file. Then some error will occur due to this.


8. What is Smart Pointer?

Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.
Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for deletion of the object when it is no longer needed.
9. Give me some messages when I press some controls in a dialog?

WM_CLOSE WM_DESTROY WM_SYSCOMMAND


10. Before to use pointer variable (anything), you have to make sure about to initialize them. Otherwise you will face some unhandled exception.

Using calloc function to create dynamic memory allocation. It will allocate memory as well as initialize them also.

int *iSamp = (int*) calloc(6, sizeof(int));

If you are using malloc function, then you will initialize them before to use.

int *iSamp = (int*) malloc(6);
zeromemory( iSamp, 6); (or)
FillMemory( iSamp, 6, 0);

11. How to avoid multiple instance of the same process?

In SDK, it is very simple. Before to create instance, check the HINSTANCE hPrevInstance in the winmain function. If it is false or null, then no one instance is there. Otherwise instance of the same process is on the screen.

int winmain(HINSTANCE hInstnce,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
if(hPrevInstance)
{
AfxMessageBox(“Another instance is running.”);
Return 0;
}
.
.
.
}

In MFC, we can use kernel object to handle this problem. Here I am using mutex to handle this one.

BOOL CModelessDialogApp::InitInstance()
{

HANDLE hMutex = ::CreateMutex(NULL,FALSE,“nat”); if(::GetLastError() == ERROR_ALREADY_EXISTS){
AfxMessageBox("Another Instance is already running.");
return FALSE;}
.
.
.
}

After that u have to close the handle in the exit instance then only the mutex object will be released.

int CModelessDialogApp::ExitInstance()
{
if(!::CloseHandle(hMutex))
AfxMessageBox("Handle is not closed");
return CWinApp::ExitInstance();
}



11. Tell me all the data types size in VC++?

int : 4 bytes
char : 1 byte
float : 4 bytes
double : 4 bytes
long : 4 bytes
short : 2 bytes
BOOL : 4 bytes
bool : 1 byte

12. Tell me about Structure Padding?

Structure Padding is nothing but add some extra padding bytes to make even storage space the structure storage space.

To reduce the padding bytes, you can group the
same data types together. Let me explain with one example.

struct name
{
int a;
char c;
int b;
char d;
};

if you get the size of this structure, then it will give 16 bytes. Before to calculate the size of the structure, first it will find the maximum size data type. After that it will allocate the memory based on the maximum size. It looks like
i0 i1 i2 i3

c0 padding bytes

i0 i1 i2 i3

c0 padding bytes

So only it will take 16 bytes long. If you want to reduce the size of the structure, you will group them with same data type. Now we can write the same structure like this,


struct name
{
int a;
int b;
char c;
char d;
};

Now we check its size, it will return 12. Let me explain, how it is possible. Only two padding bytes is enough to complete the structure memory space as even.

i0 i1 i2 i3

i0 i1 i2 i3

c0 c1 pad_bytes // 2 bytes enough


13. What stands for Afx?

Afx – Application Framework(X)

14. Describe Static member function?

Static data types can be accessed without instantiation of the class in C++. This is applicable for static functions also.
The differences between a static member function and non-static member functions are as follows.
• A static member function can access only static member data, static member functions and data and functions outside the class. A non-static member function can access all of the above including the static data member.
• A static member function can be called, even when a class is not instantiated, a non-static member function can be called only after instantiating the class as an object.
• A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual
• A static member function cannot have access to the 'this' pointer of the class.
The static member functions are not used very frequently in programs. But nevertheless, they become useful whenever we need to have functions which are accessible even when the class is not instantiated.


15. Explain inline function?

When a function is declared inline, the function is expanded at the calling block. The function is not treated as a separate unit like other normal functions.
But a compiler is free to decide, if a function qualifies to be an inline function. If the inline function is found to have larger chunk of code, it will not be treated as an inline function, but as like other normal functions.
Inline functions are treated like macro definitions by the C++ compiler. They are declared with the keyword inline as follows.

//Declaration for C++ Tutorial inline sample:
int add(int x,int y);

//Definition for C++ Tutorial inline sample:
inline int add(int x,int y)
{
return x+y;
}
In fact, the keyword inline is not necessary. If the function is defined with its body directly and the function has a smaller block of code, it will be automatically treated as inline by the compiler.
As implied, inline functions are meant to be used if there is a need to repetitively execute a small block of code, which is smaller. When such functions are treated inline, it might result in a significant performance difference.

16. Shallow Copy and Deep Copy?


17. Thread Synchronization object difference?


18. C++ Virtual function:
Properties:
C++ virtual function is,
• A member function of a class
• Declared with virtual keyword
• Usually has a different functionality in the derived class
• A function call is resolved at run-time
The difference between a non-virtual c++ member function and a virtual member function is, the non-virtual member functions are resolved at compile time. This mechanism is called static binding. Where as the c++ virtual member functions are resolved during run-time. This mechanism is known as dynamic binding.
Call Mechanism
Whenever a program has a C++ virtual function declared, a v-table is constructed for the class. The v-table consists of addresses to the virtual functions for classes and pointers to the functions from each of the objects of the derived class. Whenever there is a function call made to the c++ virtual function, the v-table is used to resolve to the function address. This is how the Dynamic binding happens during a virtual function call.




19. Difference between C Structure and C++ Structure?

• structure declaration:

In C : strut Car Maruti;

In C++ : Car Maruti;

• Structure method:

In C : does not possible

In C++ : possible as like class

Struct car
{
int a;
int fn_Test()
{
cout<};
};

or

Struct car
{
int a;
int fn_Test();
}

int car::fn_Test()
{
cout<}

• Structure Inheritance:

In C, No structure inheritance possible
In C++, structure inheritance is possible

Struct A
{
int a;
int b;
};
struct B
{
int c;
int d;
};

struct C : public A, public B
{
int fn_print()
{
cout<};
}


20. Describe structure in C++?

Structure in C++ is functionally equivalent to class. The following are possible in structure also.

1. it can have member function
struct A
{
int a;
void fn_Nat()
{
cout<<”hai”<};
};

2. structure can have characteristics of another structure. i.e., inheritance is possible
struct B : public A
{
int b;
void fn_print()
{
cout<};
};

3. all of its member are public.

4. we cant give any access specifier in it(public, private, and protected).

5. No polymorphism in structure. (i.e., Overloading, overriding)

6. we can inherit struct to a class.
struct A
{
int a;
int b;
};
class B : public A
{
int fn_print()
{
cout<};
};

21. what is aggregate data type?
An aggregate type is an array, class, or structure type which:
• Has no constructors
• Has no nonpublic members
• Has no base classes
• Has no virtual functions
Initializers for aggregates can be specified as a comma-separated list of values enclosed in curly braces. For example, this code declares an int array of 10 and initializes it:
int rgiArray[10] = { 9, 8, 4, 6, 5, 6, 3, 5, 6, 11 };

22. About Union?

Union is just like a structure. But it can have one value at a time. Real time example of union is socket address.

union aa
{
int a;
char b;
float c;
};
The size of the union is the largest member type size. So here, its size is 4. Totally 4 bytes alone is allocated for this union. If you are assigning a to 65, then access the char b, it will give the charecter A, because ascii value of A is 65.

aa test;
test.a = 65;
cout< // value of A is 65).


23. Differences between Modifier and accessor?








24. Size of the class ?

• The size of classes depends on class member variable. and vptr (if there is virtual functions).

• No of member functions (Non Virtual)doesn't affect size of class

• Empty class has 1 byte size

• If you get the size of the class member function, it will return the size of its return type

Class b
{
int fn_nat()
{
return 0;
}
};
int main(void)
{
b bb;
cout<
}
• http://codeguru.earthweb.com/forum/printthread.php?t=377183


Size of a class

What all factors determine the size of a class? Its like i created a simple class named CParent.............

class CParent
{
public:
int faint()
{
int val,nal;
return 0;
}
};

and in main function when i wanted to see the size of this class as well as its member function (faint)..........

void main()
{
CParent ptr;

cout << sizeof(ptr) << endl << sizeof (ptr.faint()) << endl;
}

It simply displayed 1 and 4. Since faint was a member function of ******* type and 2 variables reside inside that function then howcome the size of the class was still 1?

Similarly when when I used virtual keyword for that member function faint.........

class CParent
{
public:
virtual int faint()
{
int val,nal;
return 0;
}
};

then the size of the class increased from 1 to 4 what is the concept behind this? When the class size if independent of its member functions then howcome a virtual function increased the size of the class?

anantwakode 02-24-2006 06:58 AM

Re: Size of a class

Hi,

Actually Class size should be zero But ..as two different objects of same class must have different memory location ..

therefore empty classes have size 1 .

The size of classes depends on class member variable. and vptr (if there is virtual functions).

No of member functions (Non Virtual)doesn't affect size of class.

sizeof (ptr.faint()) = 4 because function ptr requires 4 bytes.

-Anant

maverick786us 02-24-2006 07:04 AM

Re: Size of a class

I know it requires 4 bites but what is the concept behind it? How do virtual functions occupy 4 bytes and how do they affect the size of class why not non virtual functions? They too occupy some space in memory?

treuss 02-24-2006 07:08 AM

Re: Size of a class

Actually the size of your class is zero. Your class does not contain any member variables, so any object of your class will not take any memory. That's the theory. In practice, objects of size zero would bring all kind of complications (e.g. a zero size object could not have a memory address), so it is put to minimum size 1.

sizeof(ptr.faint()) makes a call to ptr.faint(), which returns an int, and gives sizeof that int.

If you add a virtual function to your class, each object of your class will have a hidden pointer to a virtual function table. The table is used to resolve calls to virtual functions at runtime. Therefore the class has now the size of that pointer.

treuss 02-24-2006 07:13 AM

Re: Size of a class

Quote:
Originally Posted by maverick786us
I know it requires 4 bites but what is the concept behind it? How do virtual functions occupy 4 bytes and how do they affect the size of class why not non virtual functions? They too occupy some space in memory?
sizeof(some class) always gives you the size of one object of that class. In that sense, functions do not take memory, because the code for a function is used by all objects. There is no way to calculate the size of the code a function will take, if that is what you are after. Memory for local variables within a function will only be allocated on the stack if the function is called. Thus they also do not affect what the sizeof operator returns.

Vedam Shashank 02-24-2006 07:25 AM

Re: Size of a class

Member functions do not add count to the size of an object of a class.

I doubt that u can determine the size of an object of a class by just looking at it.

For more see..
C++ Structure: Why returns 'sizeof()' a bigger size than the members actually need?


As for size of a function, i am not sure if u can apply sizeof to determine that.

Vedam Shashank 02-24-2006 07:29 AM

Re: Size of a class

From the standards...
Quote:
5.3.3 Sizeof [expr.sizeof]
1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand
is either an expression, which is not evaluated, or a parenthesized typeid.
The sizeof operator shall not
be applied to an expression that has function or incomplete type, or to an enumeration type before all its
enumerators have been declared, or to the parenthesized name of such types, or to an lvalue that designates
a bitfield.
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the
result of sizeof applied to any other fundamental type (3.9.1) is implementationdefined.
[Note: in particular,
sizeof(bool) and sizeof(wchar_t) are implementationdefined.
69) ] [Note: See 1.7 for
the definition of byte and 3.9 for the definition of object representation. ]


Graham 02-24-2006 08:30 AM

Re: Size of a class

Just to complete the picture: if a class has no data members or virtual functions, sizeof must report its size as at least 1 (as has been pointed out) - however it is allowed to have zero size if it is used as a base class. So, if B is an empty class, and D (derived from B) contains an int, then sizeof(B) == 1, but sizeof(D) == sizeof(int) (not sizeof(int) + 1). (All numbers are illustrative...)

sunnypalsingh 02-24-2006 09:13 AM

Re: Size of a class

sizeof class also depends on the order in which you lay out members in the class.

RoboTact 02-24-2006 09:33 AM

Re: Size of a class

And there are about no applications of sizeof() in C++.

Vedam Shashank 02-24-2006 10:09 AM

Re: Size of a class

Quote:
Originally Posted by RoboTact
And there are about no applications of sizeof() in C++.


Like u said practically there are no uses of sizeof(...), why was it ever there. Of what use was it earlier???

RoboTact 02-24-2006 10:13 AM

Re: Size of a class

Why, you can save structures in binary files (which you shouldn't do anyway) and get sizes of arrays.

SuperKoko 02-24-2006 10:30 AM

Re: Size of a class

sizeof was much used by C programs which were allocating memory through malloc, because they needed to know the size of the allocated block.

sizeof is still useful in C++, to provide low level memory management.
It is probably used in STL.
For example, a specialization for std::copy may be provided for builtin types pointers.
In that case, the number of elements is multiplied by sizeof(BuiltinType) and passed to memcpy.

To get an idea of sizeof uses, you can search it in your headers/modules of your compiler standard library and STL.

sunnypalsingh 06-01-2006 10:43 AM

Re: Size of a class

Quote:
Originally Posted by Graham
Just to complete the picture: if a class has no data members or virtual functions, sizeof must report its size as at least 1 (as has been pointed out) - however it is allowed to have zero size if it is used as a base class. So, if B is an empty class, and D (derived from B) contains an int, then sizeof(B) == 1, but sizeof(D) == sizeof(int) (not sizeof(int) + 1). (All numbers are illustrative...)


Sorry I am picking up an old thread.

But how can a size be 0?? Plz explain.

SuperKoko 06-01-2006 10:53 AM

Re: Size of a class

Quote:
Originally Posted by sunnypalsingh
But how can a size be 0?? Plz explain.

It means that adding such empty base class doesn't change the size of the derived class:
Code:

class Base1 {};
class Base2 {};
class Base3 {};
class Base4 {};

struct Derived:Base1,Base2,Base3,Base4 {
char c[2];
};

This Derived class may have a size of 2 on some compilers.
Which is smaller than the sum of the sizes of the base classes.




How to map the class with dialog? What are the steps to be followed?

1. The class must derive from the CDialog class.

2. In the class definition file, at the constructor prototype, you have to give the Dialog ID to the CDialog constructor like below

CMyDialog::CMyDialog() : CDialog(IDD_DIALOG1, NULL)
{
}

3. If you want to add event handler function , then you will follow this instructions. Otherwise you will get error.

DECLARE_MESSAGE_MAP() macro should be placed the class declaration gets closed.

BEGIN_MESSAGE_MAP(your class, base class)
//add your message mapping here
ON_CONTROL(WM_COMMAND, BN_CLICKED, IDOK, OnOK)
END_MESSAGE_MAP()

These statements must be inserted into your class
definition file for mapping the messages with its event handler function.

4. It may be have the following function

OnInitDialog() – this is the next function to be
executed after its class
constructed.

DoDataExchange() – If you have some controls on the
dialog and needed to take a
variable for that controls, then
you will add this function.

The below class will explain all the details what mentioned in the above instruction.

Class Declaration

#pragma once

class CMyDialogDlg : public CDialog
{

public:
CMyDialogDlg();
virtual ~CMyDialogDlg(void);

protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support

public:
virtual BOOL OnInitDialog();
afx_msg void OnOK();
afx_msg void OnCancel();

DECLARE_MESSAGE_MAP()
};



Class Definition :

#include "StdAfx.h"
#include "CDialogTest.h" //application class
#include "mydialogdlg.h" //your own class


CMyDialogDlg::CMyDialogDlg()
: CDialog(IDD_DIALOG_NEW, NULL)
{

}

CMyDialogDlg::~CMyDialogDlg(void)
{
}

void CMyDialogDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}

BOOL CMyDialogDlg::OnInitDialog()
{
return TRUE;
}

BEGIN_MESSAGE_MAP(CMyDialogDlg, CDialog)
ON_CONTROL(BN_CLICKED, IDOK, ONOK)
ON_CONTROL(BN_CLICKED, IDCANCEL, OnCancel)
END_MESSAGE_MAP()

void CMyDialogDlg::OnOK()
{
AfxMessageBox("hai");
CDialog::OnOK();
}

void CMyDialogDlg::OnCancel()
{
CDialog::OnCancel();
}


























Some Useful Sites:


www.codeguru.com
www.codeproject.com
www.codersource.com

http://www.icce.rug.nl/documents/cplusplus/
www.w3school.com


http://www.functionx.com/visualc/
http://www.microsoft.com/msj/1098/vc6/vc6.aspx
http://www.samspublishing.com/library/content.asp?b=Visual_C_PlusPlus&seqNum=62&rl=1
http://www.codepedia.com/1/Cpp
http://www.go4expert.com/forums/forumdisplay.php?f=60
http://www.cplusplus.com/doc/tutorial/templates.html

http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=169&rl=1

http://www.devarticles.com/c/b/Cplusplus/

கருத்துகள் இல்லை:

கருத்துரையிடுக