7/1/08

Miscellaneous VC++, Windows Questions

4. How to access document object from view ?
GetDocument()

5. What is the entry point for window based applications ?
WinMain()

6. Explain the flow for a simple win32 based application ?
WinMain() -> Wnd class registration ->window creation- > loop

7. How to handle command line arguements from simple MFC application ?

8. What is model and modeless dialog box ? Give some examples?

9. How to create open & save dialogs ?
CFileDialog with true or false value;

10.What is CSingleDocTemplate?
Used to bind SDI classs

11.What is the difference between hinsrtance and hprevinstance in WinMain function?
12.Explaing about MDI and CMultiDocTemplate ?

13.Tell me the different controls in MFC ?
14. What is the use of OninitDialog ?

15. What is the use of UpdateData funciton ?
Saving data from control to variable and vice versa
16.What is the difference between GetMessage and PeekMessage ?
1st one constantly seeks queue for message, peekmessage returns immidiately
17.How to update all the views whenver document got updated ?
UpdateAllViews()
18.How to handle RTTI in MFC ?
DECLARE_DYNCREATE /IMPLEMENT_DYNACREATE
19.What is serialization ?which function is responsible for serializing data ?
Storing /retrieving object to/from disk
Doc::Serialize

20.What is CArchive class dowes?
Object storage in Binary format

21.What is thread & process?

22.Explain about different kinds of threads in MFC?
UI thread/ Worker thread

23.Tell me about different kinds of synchranization objects ?
Creatical section/Mutex/Semaphore/Event

24.what is the use of Mutex and critical section ?
25.What is socket?
26.What is the difference between Synchronous sockets and asynchronous sockets?
27.Have you ever used win32 APIs ?
28.What is the difference between ANSI Code and UNICODE ?
29.What is the difference between regular dlls and extended dlls?
30.what is the use of AFX_MANAGE_STATE ?
31. What’s the difference between PostMessage and SendMessage?
32. Describe the Document/View architecture.
33. What’s the difference between Modal and Modeless Dialog?
34. How to create a Modeless Dialog?
35. How to setup a timer?
36. Name the Synchronization objects.
37. What is a critical section and how is it implemented?
38. What is CMutex?
39. Given two processes, how can they share memory?
38. What is a message map, and what is the advantage of a message map over virtual functions?
40. What is the difference between ASSERT and VERIFY?
41. Why wizards generate enum IDD for dialogs? [Added by Shabbir]


GetMessage function waits for a message to be placed in the queue before returning where as PeekMessage function does not wait for a message to be placed in the queue before returning.


The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and then returns without waiting for the thread to process the message.

The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message.


_pModeless is a variable of type CDialog or any of its descendants.

m_pModeless->Create(IDD_DIALOG1, this);
m_pModeless->ShowWindow(SW_SHOW);

this pointer as a paramter suggest we are creating a child dialog of the current dialog/window.


Name the Synchronization objects ?
________________________________________
Following are the synchronization objects
1) Critical Section
2) Event
3) Mutex
4) Semaphore

Classes provided for above synchronization objects are:

1) CCriticalSection
2) CEvent
3) CMutex
4) CSemaphore


What Is CMutex ?
________________________________________
An object of class CMutex represents a “mutex” — a synchronization object that allows one thread mutually exclusive access to a resource. Mutexes are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CMutex object to control the linked list, only one thread at a time can gain access to the list.

To use a CMutex object, construct the CMutex object when it is needed. Specify the name of the mutex you wish to wait on, and that your application should initially own it. You can then access the mutex when the constructor returns. Call CSyncObject::Unlock when you are done accessing the controlled resource.

An alternative method for using CMutex objects is to add a variable of type CMutex as a data member to the class you wish to control. During construction of the controlled object, call the constructor of the CMutex data member specifying if the mutex is initially owned, the name of the mutex (if it will be used across process boundaries), and desired security attributes.

To access resources controlled by CMutex objects in this manner, first create a variable of either type CSingleLock or type CMultiLock in your resource’s access member function. Then call the lock object’s Lock member function (for example, CSingleLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, use the lock object’s Unlock member function (for example, CSingleLock::Unlock), or allow the lock object to fall out of scope

The main difference between ASSERT and VERIFY is when you compile the release build of the program.

ASSERT will not be present in the release build version of the executables/dlls, and its expression that would have been evaluated will be deleted.

VERIFY will be present in the release build version of the executables/dlls but its expression that would have been evaluated will be left intact.

Threads are similar to processes, but differ in the way that they share resources. Threads are distinguished from processes in that processes are typically independent, carry considerable state information and have separate address spaces. Threads typically share the memory belonging to their parent process.

what is the use of AFX_MANAGE_STATE ?
________________________________________
By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:
AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.

If all your resources lies in the single DLL you can even change the default handle to the DLL handle with the help of AfxSetResourceHandle function.

What is CArchive class does?
________________________________________
As a quote from MSDN.
Quote:
Originally Posted by MSDN
The CArchive class allows you to save a complex network of objects in a permanent binary form (usually disk storage) that persists after those objects are deleted. Later you can load the objects from persistent storage, reconstituting them in memory. This process of making data persistent is called “serialization.”


How to handle command line arguements from simple MFC application ?
________________________________________
m_lpCmdLine Corresponds to the lpCmdLine parameter passed by Windows to WinMain. Points to a null-terminated string that specifies the command line for the application. Use m_lpCmdLine to access any command-line arguments the user entered when the application was started. m_lpCmdLine is a public variable of type LPTSTR.

Example
Code: CPP

BOOL CMyApp::InitInstance()
{
// ...

if (m_lpCmdLine[0] == _T('\0'))
{
// Create a new (empty) document.
OnFileNew();
}
else
{
// Open a file passed as the first command line parameter.
OpenDocumentFile(m_lpCmdLine);
}

// ...
}


Memory Management
Q: What is the effective way of DIB files management?
Q: What should you be aware of if you design a program that runs days/weeks/months/years?
DLL

Q: What are the advantages of using DLL's?
Q: What are the different types of DLL's?
Q: What are the differences between a User DLL and an MFC Extension DLL?
Multiple Inheritance

Q: What do you have to do when you inherit from two CObject-based classes?
Q: What are the additional requirements for inheritance from CWnd-based classes?
Multithreading

Q: What is a "mutex"?
Q: What's the difference between a "mutex" and a "critical section"?
Q: What might be wrong with the following pseudo-code:
FUNCTION F
BEGIN
INT I=2
DO
I = I + 1
IF I = 4 THEN BREAK
END DO
END
Q: What is a deadlock ?
Q:How can we create thread in MFC framework?
Q: What types of threads are supported by MFC framework?
Message Map

Q: When ON_UPDATE_COMMAND_UI is called? (message may vary)
Q: What is a "hook"?
Exception Handling

Q: (another stupid one) What are the difference between MFC Exception macros and C++ exception keywords?
Reusable Control Class

Q: How would you set the background of an edit control to a customized color?
Q: What is Message Reflection? How could you accomplish the above task using message reflection?
MFC
Q: What is the command routing in MFC framework?
Q: What's the purpose of CView class? CDocument class? What are relationships between them?
Q: What class is responsible for document template in MDI application?
Q: What function must be used to add document template?
Q: What the main objects are created for SDI and MDI applications?
Misc.
Q: Application fails. We have a loop for 800,000. It fails on 756,322. How can we get an information before it fails.
Q: Our Debug version works fine, but Release fails. What should be done?
________________________________________
A: You don't have to mention all differences. Some of them are:
1. Lack of Unicode implementation for most of the functions of Win95.
2. Different extended error codes.
3. Different number window and menu handles.
4. Windows 95 implements some window management features in 16 bits.
5. Windows 95 uses 16-bit world coordinate system and the coordinates restricted to 32K.
6. Deletion of drawing objects is different.
7. Windows 95 does not implement print monitor DLLs of Windows NT.
8. Differences in registry.
9. Windows 95 does not support multiprocessor computers.
10. NT implementation of scheduler is quite different.
11. Different driver models.
12. Win95 was built with back-compatibility in mind and ill-behaving 16-bit process may easily corrupt the system.
13. Win95 starts from real DOS, while WinNT uses DOS emulation when one needs a DOS.
14. Win95's FAT is built over 16-bit win3.1 FAT (not FAT32!) (actually, Win95's FAT contains two FATs)
A: Memory-mapped file is the best choice for device-independent bitmaps. MMF allows to map the file to RAM/SWAP addresses and to let Windows handle all load/unload operations for the file.
A: When your program should run for a long time, you should be careful about heap allocations, because if you use new/delete intensively in your application, the memory becomes highly fragmented with a time. It is better to allocate all necessary memory in this case that many times small blocks. You should be especially careful about CString class which allocates permanent
A: You may mention the following advantages:
1. DLLs are run-time modular. DLL is loaded when the program needs it.
2. Used as a code sharing between executables.
A: Extension, Regular and pure Win32 DLL (without MFC)
A: Extension DLL supports a C++ interface, i.e. can export whole C++ classes and the client may construct objects from them. Extension DLL dynamically links to MFC DLLs (those which name starts with MFC??.DLL) and to be synchronous with the version it was developed for. Extension DLL is usually small (simple extension DLL might be around 10K) Regular DLL can be loaded by any Win32 environment (e.g. VB 5) Big restriction is that regular DLL may export only C-style functions. Regular DLLs are generally larger. When you build a regular DLL, you may choose a static link (in this case MFC library code is copied to your DLL) and dynamic (in this case you would need MFC DLLs to be presented on the target machine)
A: First of all, this is a bad idea does not matter what tells you interviewer. Secondly, if you forced to use condemned rhombus structure, read Technical Note 16 in MSDN, which discusses why MFC does not support multiple inheritance and what to do in case you still need it (there are a few problems with CObject class, such as incorrect information, returned by IsKindOf() of CObject for MI, etc.)
A: Again, this is the bad idea. Try to find alternative solution. Anyway, if you have to multiply inherit from CWnd-based class, the following are additional requirements to the above conditions (again, this is extremely bad question for interview!!!):
o There must be only one CWnd-derived base class.
o The CWnd-derived base class must be the first (or left-most) base class.
A: Mutexes are the mechanism of process synchronization that might be used to synchronize data across multiple processes. Mutex is a waitable object while a critical section is not. Mutexes are significantly slower than critical sections.
A: Critical section provides synchronization means for one process only, while mutexes allow data synchronization across processes.
A: This code is not thread safe. Suppose one thread increments I to 3 and then returns to the beginning of DO statement. Then it increments I to 4 and now context switch happens. Second thread increments I to 5. From this moment the code shown will execute forever until some external force intervention. Solution is obviously using some synchronization object to protect I from being changed by more than one thread.
A: A deadlock, very simply, is a condition in which two or more threads wait for each other to release a shared resource before resuming their execution. Because all threads participating in a deadlock are suspended and cannot, therefore, release the resources they own, no thread can continue, and the entire application (or, worse, more than one application if the resources are shared between threads in multiple applications) appears to hang.
A: Using AfxBeginThread.
A: Working thread and windows thread. Working thread usually does not have a user interface and easier to use. Windows thread has an user interface and usually used to improve responsiveness of the user input.
A: When a user of your application pulls down a menu, each menu item needs to know whether it should be displayed as enabled or disabled. The target of a menu command provides this information by implementing an ON_UPDATE_COMMAND_UI handler.
A: A point in the Windows message-handling mechanism where an application can install a subroutine to monitor messages. You need hooks to implement your own Windows message filter.
A: Stupid question. There are few differences such as names, different last throw and so on. Probably, the major difference is that MFC macros have born when C++ did not have exception handling and based on C exception mechanism (actually, MFC macros may accept exception of only CException class or class, derived from CException, where as C++ exception mechanism accepts exception of ANY type)
A: You have several choices, but the simplest one is subclassing. Kruglinski in his "Inside Visual C++" describes pretty well this process. Generally, you derive the class from none control class, override the messages you want (like WM_CTLCOLOR) and then in init function like OnInitialUpdate of CDialog, subclass the control with SubclassDlgItem().
A: See Technical Note 62 of MSDN. Usually, message is handled in the parent class that means you have to override message handler for each parent. Sometimes it is nice to handle a message in the control itself, without parent invocation. Such handling mechanism is called message reflection. Control "reflects" message to itself and then processes it. Use ON__REFLECT macro to create a reflected message.
A: CView => CDocument => CFrameWnd => CWinApp
A: The CView class provides the basic functionality for user-defined view classes. A view is attached to a document and acts as an intermediary between the document and the user: the view renders an image of the document on the screen or printer and interprets user input as operations upon the document. The CDocument class provides the basic functionality for user-defined document classes. A document represents the unit of data that the user typically opens with the File Open command and saves with the File Save command. Users interact with a document through the CView object(s) associated with it. A view is a child of a frame window. The relationship between a view class, a frame window class, and a document class is established by a CDocTemplate object. A view can be attached to only one document, but a document can have multiple views attached to it at once.
A: CMultiDocTemplate.
A: AddDocTemplate.
A: CWinApp - application object. For MDI application with New document implementation CDocTemplate, CDocument, CView, CMainFrame. If your application is SDI, your CMainFrame class is derived from class CFrameWnd. If your application is MDI, CMainFrame is derived from class CMDIFrameWnd. For MDI application CMDIChildWindow is also created.
A: You could think of several way to debug this:
• Set the condition in debugger to stop when loop is passed around 756321 times.
• Throw an exception within a loop (may be not the best idea since exception does not show you the exact location of the fail.
• Create a log file and to put detailed information within a loop.
A: There are four differences between debug and release builds:
1. heap layout (you may have heap overwrite in release mode - this will cause 90% of all problems),
2. compilation (check conditional compilation statements, assertion functions etc.),
3. pointer support (no padding in release mode which may increase chances of a pointer to point into sky) and
4. optimization. Check the project settings.

1. What is IUnknown? What methods are provided by IUnknown? It is a generally good idea to have an answer for this question if you claim you know COM in your resume. Otherwise, you may consider your interview failed at this point. IUnknown is the base interface of COM. All other interfaces must derive directly or indirectly from IUnknown. There are three methods in that interface: AddRef, Release and QueryInterface.
2. What are the purposes of AddRef, Release and QueryInterface functions? AddRef increments reference count of the object, Release decrements reference counter of the object and QueryInterface obtains a pointer to the requested interface.
3. What should QueryInterface functions do if requested object was not found? Return E_NOINTERFACE and nullify its out parameter.
4. How can would you create an instance of the object in COM? Well, it all depends on your project. Start your answer from CoCreateInstance or CoCreateInstanceEx, explain the difference between them. If interviewer is still not satisfied, you’ll have to explain the whole kitchen behind the scenes, including a difference between local server and inproc server, meaning and mechanism of class factory, etc. You may also mention other methods of object creation like CoGetInstanceFromFile, but discussion will likely turn to discussion of monikers then.
5. What happens when client calls CoCreateInstance? Again, all depends on the level of detail and expertise of interviewer. Start with simple explanation of class object and class factory mechanism. Further details would depend on a specific situation.
6. What the limitations of CoCreateInstance? Well, the major problems with CoCreateInstance is that it is only able to create one object and only on local system. To create a remote object or to get several objects, based on single CLSID, at the same time, one should use CoCreateInstanceEx.
7. What is aggregation? How can we get an interface of the aggregated object? Aggregation is the reuse mechanism, in which the outer object exposes interfaces from the inner object as if they were implemented on the outer object itself. This is useful when the outer object would always delegate every call to one of its interfaces to the same interface in the inner object. Aggregation is actually a specialized case of containment/delegation, and is available as a convenience to avoid extra implementation overhead in the outer object in these cases. We can get a pointer to the inner interface, calling QueryInterface of the outer object with IID of the inner interface.
8. C is aggregated by B, which in turn aggregated by A. Our client requested C. What will happen? QueryInterface to A will delegate request to B which, in turn, will delegate request for the interface to C. This pointer will be returned to the client.
9. What is a moniker ? An object that implements the IMoniker interface. A moniker acts as a name that uniquely identifies a COM object. In the same way that a path identifies a file in the file system, a moniker identifies a COM object in the directory namespace.
10. What’s the difference, if any, between OLE and COM? OLE is build on top of COM. The question is not strict, because OLE was built over COM for years, while COM as a technology was presented by Microsoft a few years ago. You may mention also that COM is a specification, while OLE is a particular implementation of this specification, which in today’s world is not exactly true as well, because what people call COM today is likely implementation of COM spec by Microsoft.
11. What’s the difference between COM and DCOM? Again, the question does not require strict answer. Any DCOM object is yet a COM object (DCOM extends COM) and any COM object may participate in DCOM transactions. DCOM introduced several improvements/optimizations for distributed environment, such as MULTI_QI (multiple QueryInterface()), security contexts etc. DCOM demonstrated importance of surrogate process (you cannot run in-proc server on a remote machine. You need a surrogate process to do that.) DCOM introduced a load balancing.
12. What is a dual interface? Dual interface is one that supports both - IDispatch interface and vtbl-based interface. Therefore, it might be used in scripting environment like VBScript and yet to use power and speed of vtbl-based interface for non-scripting environment. Discussion then may easily transform into analyzing of dual interface problems - be prepared to this twist.
13. Can you have two dual interfaces in one class? Yes. You may have two dual interfaces in one class, but only one of them may be default. The bottom line is that you cannot work with two dual interfaces at the same time due to nature of dual interface! To support two dual interfaces in VB you would write something like:
14. dim d1 as IDualInterface1
15. dim d2 as IDualInterface2
16. set d1 = new MyClassWithTwoDuals
17. set d2 = d1

In ATL’s class you would have to use macro COM_INTERFACE_ENTRY2(IDispatch,
IDualInterface1), to distinguish between different dual interfaces.
18. What is marshalling by value? Some objects can essentially be considered static: regardless of which methods are called, the state of the object does not change. Instead of accessing such an object remotely, it is possible to copy the static state of the object and create a new object with the same state information on the caller side. The caller won’t be able to notice the difference, but calls will be more efficient because they do not involve network round trips. This is called “marshaling by value”.
19. What is a multi-threaded apartment (MTA)? Single-threaded apartment (STA)? This is pretty difficult question to describe shortly. Anyway, apartments were introduced by Microsoft in NT 3.51 and late Windows 95 to isolate the problem of running legacy non-thread safe code into multithreaded environment. Each thread was “encapsulated” into so called single-threaded apartment. The reason to create an object in apartment is thread-safety. COM is responsible synchronize access to the object even if the object inside of the apartment is not thread-safe. Multithreaded apartments (MTA, or free threading apartment) were introduced in NT 4.0. Idea behind MTA is that COM is not responsible to synchronize object calls between threads. In MTA the developer is responsible for that. See “Professional DCOM Programming” of Dr. Grimes et al. or “Essential COM” of Don Box for the further discussion on this topic.
20. Let’s assume we have object B and aggregated object C (in-proc server), created by B. Can you access any interface of B from C? What’s the difference between aggregated and contained objects? Yes, you can. This is fundamental postulate of COM: “If you can get there from here, you can get there from anywhere”, i.e. QI’ing for IUnknown you may proceed and to get a pointer to any other interface, supported by the object. Aggregated object exposes its interface directly, without visible intervention of the object container. Contained object is created within the object container and its interfaces might be altered or filtered by the object container.
21. What is ROT ? GIT ? Count pros and cons of both. By definition, running object table (ROT) is a globally accessible table on each computer that keeps track of all COM objects in the running state that can be identified by a moniker. Moniker providers register an object in the table, which increments the object’s reference count. Before the object can be destroyed, its moniker must be released from the table. Global Interface Table (GIT) allows any apartment (either single- or multi-threaded) in a process to get access to an interface implemented on an object in any other apartment in the process.
22. If you have an object with two interfaces, can you custom marshal one of them? No! The decision to use custom marshaling is an all-or-nothing decision; an object has to custom marshal all its interfaces or none of them.
23. Is there a way to register in-proc server without regsvr32.exe? Yes. Call DllRegisterServer() from the client. Do not forget to call DLLUnregisterServer() from the same client. You may also use Registrar object for the same purpose or use direct manipulation of the windows registry.
24. What is VARIANT? Why and where would you use it? VARIANT is a huge union containing automation type. This allows easy conversion of one automation type to another. The biggest disadvantage of VARIANT is size of the union.
25. How can you guarantee that only remote server is ever created by a client? Create an object (call CoCreateObjectEx()) with CLSCTX_REMOTE_SERVER flag.
26. What is __declspec(novtable)? Why would you need this? __declspec(novtable) is a Microsoft’s compiler optimization. The main idea of this optimization is to strip the vtable initialization code from abstract class (for abstract class the vtable is empty, while it is initialized in contructor)
27. What is an IDL? IDL stands for Interface Definition Language. IDL is the language to describe COM interfaces.
28. What is In-proc? In-proc is in-process COM object, i.e. COM object that implemented as DLL and supposed to be hosted by a container. When you have to instantiate the in-proc object remotely, you may use DLLHost.exe application that was design specially for this purpose.
29. What is OLE? OLE is an object and embedding first implementation of COM spec available from MS before COM was officially named COM.
30. Give examples of OLE usage. The most famous examples are probably drag and drop and structured storage implementations.
31. What are 2 storage types for composite document? Storage and Stream.
32. Is .doc document a compound document? Is it a structured storage? Compound document is a document that contains information about other documents hosted in this document. All office documents _may_ be compound documents, but may be not. Word documents from version 6.0 and up are stored as structured storage.

What’s the difference between PostMessage and SendMessage?


Describe the Document/View architecture.


What’s the difference between Modal and Modeless Dialog?


How to create a Modeless Dialog?


How to setup a timer?


Name the Synchronization objects.


What is a critical section and how is it implemented?


What is CMutex?


Given two processes, how can they share memory?


What is a message map, and what is the advantage of a message map over virtual functions?


What is the difference between ASSERT and VERIFY?

1. What is the base class for MFC Framework ?
2. If i derive a new class from CObject what are the basic features my derived wil get ?
3. What is the use of CCmdTarget ?
4. What is document-view architecture ? Give me one real time example for SDI ?
5. Can you explaing the relashionship between document,frame and view ?
6. How to access document object from view ?
5. What is the entry point for window based applications ?
6. Explain the flow for a simple win32 based application ?
7. How to handle command line arguements from simple MFC application ?
8. What is model and modeless dialog box ? Give some examples?
9. How to create open & save dialogs ?
10.What is CSingleDocTemplate?
11.What is the difference between hinsrtance and hprevinstance in WinMain function?
12.Explaing about MDI and CMultiDocTemplate ?
13.Tell me the different controls in MFC ?
14. What is the use of OninitDialog ?
15. What is the use of UpdateData funciton ?
16.What is the difference between GetMessage and PeekMessage ?
17.How to update all the views whenver document got updated ?
18.How to handle RTTI in MFC ?
19.What is serialization ?which function is responsible for serializing data ?
20.What is CArchive class dowes?
21.What is thread & process?
22.Explain about different kinds of threads in MFC?
23.Tell me about different kinds of synchranization objects ?
24.what is the use of Mutex and critical section ?
25.What is socket?
26.What is the difference between Synchronous sockets and asynchronous sockets?
27.Have you ever used win32 APIs ?
28.What is the difference between ANSI Code and UNICODE ?
29.What is the difference between regular dlls and extended dlls?
30.what is the use of AFX_MANAGE_STATE ?

No comments:

ITUCU