Top Banner

of 85

C++ Q2

May 30, 2018

Download

Documents

mohan
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/14/2019 C++ Q2

    1/85

    C++What is the namespace?A namespace allows you to resolve conflict of the global identifiers when you useDescribe what a SubClassing?Subclassing allows us to reuse code, which saves us time. Its also a Technique used to intercept Windows

    messages

    What is inline function ?

    inline keyword before name of the function allows the compiler to insert a copy of the functionbody into each place the function is called. Therefore, the size of the code is increasing, but

    speed of execution is also increasing. No matter how you designate a function as inline, it is arequest that the compiler is allowed to ignore. You have to play with it to see what is best so

    dont ignore. Also unlike macros, argument types are checked, and necessary conversions areperformed correctlyinline functions canprevent thrashing: When f() calls g(), the code might be on two distinct pages ofmemory, but when the compiler procedurally integrates the code of g() into f(), they are often on the samepage, so the working set size (number of pages that need to be in memory at once) may go down even if theexecutable size goes up.When should I use references, and when should I use pointers?

    Use references when you can, and pointers when you have to. References are usually preferred overpointers whenever you don't need "reseating"(i.e, Unlike a pointer, once a reference is bound to an object, itcan notbe "reseated" to another object). This usually means that references are most useful in a class'spublic interface .

    Is there another way to tell the compiler to make a member function inline other than using inlinekeyword?Yep: define the member function in the class body itself:

    What is a reference?

    A reference is a quantity that holds the address of an object but behaves syntactically like that object. Areference cannot exist without object and must be initialized. The reference is the referent, so changing thereference changes the state of the referent.

    A Reference is an "lvalue" (something that can appear on the left hand side of an assignment operator).

    What happens if you return a reference?

    The function call can appear on the left hand side of an assignment operator.

    What's 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 beaccessed by member functions and friends of that class. Means that base class is sealed-off from

    subsequent derivations* A member (either data member or member function) declared in a protected:section of a class can only beaccessed by member functions and friends of that class, and by member functions and friends of derivedclasses* A member (either data member or member function) declared in a public: section of a class can beaccessed by anyone.

  • 8/14/2019 C++ Q2

    2/85

    Why Do we need Virtual Base Class?

    InOrder to save space and Avoid Ambiguities in case of multiple inheritence i.e, virtual base class ifinherited more than once via different path then only one copy of data member presents which isshared by all the derived classes that use it as a virtual base.

    Why Virtual Function?

    Is to have derived classes inherit a function interface as well as a default implementation. But its not mandatory to

    redefine in its derived class. A virtual function allows derived classes to replace the implementation provided by the baseclass

    Why should be base class destructor be virtual

    If you destroy an object through a pointer or reference to a base class and the base class destructor is not

    virtual then the derived class destructor are not executed and the destruction might not be complete. If not itleads to memory leaks.

    Usage of Static Variable?

    Only one copy is created and shared by all the objects of the class. Defined outside the class, initialized to Zero .Life timewill be the entire program. static variables exist without creating an object

    Static Function: Can access or refer to only static data members of a class, Accessable through a class name instead ofan object. If your function is static, it cannot access non static functions

    Difference between Static and Global Variable?

    Static Variable: is accessible only to all functions defined in the same fileGlobal Variable: is accessible by all functions defined even from different files.Can we pass class variables to static functions?Yes. A class variable is nothing but a static variable. So from static function, static variables can be very wellaccessedExplain on Const?Any function of a class which does not modify the data member of class within it should add a const at theend of a function ( it even cannot call any member function that are not constant). It makes the function

    read-onlyNote: Keyword Mutable can change the value of data inside a const member function

    To define a const statement: Const int MAX=100; const distance d3(10,6); //the values 10 and 6 cannot be changed

    Note: the const members must be initialized in the constructors member initializer lists

  • 8/14/2019 C++ Q2

    3/85

    Why we should implement copy constructor?

    To perform Deep Copy. It allows you to make copies of all fields and makes copies of dynamically allocatedmemory pointed to by the fields. (Ex. userdefined copy constructor and overloaded Assignment operator)

    Note: copy constructor will always take a reference to an object of its own class as its argument.If not it willresult in calling the copy constructor recursively. And you cannot return a value from it. It is called duringa) initialization of one object with another object of same class b) passing an object by value c) returing anobject by value.Why Friend Function?If we want to give a non-member function unlimited access to the members of a class we would declaresuch a function as a friend of that class. (ie friend functions are able to access private and protected datamembers)Friend property is not Inherited, not transitive and acts only in one directionNote: here you have to pass object as parameter in order to access the class data members.What is an object?A region of storage with associated semantics.

    What's the difference between the keywords struct and class?The members and base classes of a struct are public by default, while in class, they default to private.struct and class are otherwise functionally equivalent.

    Define Encapsualtion?

    Encapsulation puts a firewall around the chunk, which prevents other chunks from accessing it.Designing a clean interface and separating that interface from its implementation merely allows users to usethe interface. But encapsulating (putting "in a capsule") the implementation forces users to use the interface.Encapsulation doesnt provide security, Encapsulation prevents mistakes, not espionageCan one constructor of a class call another constructor of the same class to initialize the this

    object?No.Is the default constructor for Fred always Fred::Fred()?No.

    A "default constructor" is a constructor that can be calledwith no arguments. One example of this is aconstructor that takes no parameters:class Fred

    {public:Fred(); // Default constructor: can be called with no args

    // ...};

    Another example of a "default constructor" is one that can take arguments, provided they are given defaultvalues:

    class Fred{public:Fred(int i=3, int j=5); // Default constructor: can be called with no args

    // ...};

  • 8/14/2019 C++ Q2

    4/85

    Should you use the this pointer in the constructor?Some people feel you should not use the this pointer in a constructor because the object is not fully formedyet. However you can use this in the constructor, but be carefull .Here is something that always works : the {body} of a constructor (or a function called from the constructor)can reliably access the data members declared in a base class and/or the data members declared in theconstructor's own class. This is because all those data members are guaranteed to have been fully

    constructed by the time the constructor's {body} starts executingHere is something that neverworks : the {body} of a constructor (or a function called from the constructor)cannotget down to a derived class by calling a virtual member function that is overridden in the derivedclass. If your goal was to get to the overridden function in the derived class, you won't get what you wantCan you initialize static member data in the constructor's initialization list?No. Because you must always explicitlydefine your class's static data members.

    What's the order that local objects are destructed?

    First constructed, last destructed . Here b's destructor will be executed first, then a's destructor:void userCode(){Fred a;

    Fred b; // ...}

    What's the order that objects in an array are destructed?

    First constructed, last destructed. Here in the example the order for destructors will be a[9], a[8], ..., a[1],a[0]:void userCode(){Fred a[10];

    // ...

    }

    Should I explicitly call a destructor on a local variable?

    NO. The destructor will get called again at the close } of the block in which the local was created

    What is static binding and dynamic binding?

    SB:refers to an entity existingin different physical form simultaneously. Binding takes place at compile time

    based on the type of object.DB:refers to an entity existing changingits form depending on the circumstances. Binding takes place atruntime based on the context of the object.What you cannot inherit ?1)Construtor & Destructor 2) New & = Operators 3)Friend Relationship 4) Private Data member/ memberfunctionCan you instantiate an Abstract Class?

  • 8/14/2019 C++ Q2

    5/85

    No. Because they represent no real objects the only represent Design-objects. These classes are used tostore common properties of their subclasses. They will contain pure virtual function. Technically this class isan incomplete class and hence its object cannot be created. Therefore we are forcing derived functions tooverride that functions.Why we should not return reference or pointer to a local variable?Because with local variable it goes out of scope (since its allocated in the stack)

    With Pointers, I leads giving raise to a memory leak (since its allocated in the heap).Can you instantiate Cobject?It cannot be instantiated directly since the constructor is the protected member of class.It can only beinherited. It provides support to serialization but does not support RTTI.Why is it important to use reference during "catch" statement?Exception is always thrown by value .If not reference these will invoke copy constructor and copies theexception object unnessarily. Therefore to save space use a references.

    What are the advantage and disadvantage of using exception handling?Disadvantage: implementing exception-handling mechanism imposes slight overhead. Advantage provides"bullet-proof" program.How procompiled header work in windows?

    After the header files included in the StdAfx.cpp and StdAfx.h are processesed, the preprocessor saves asnapshot of its internal state as an .PCH file. Since processing all those state headers repeatedly take longstime for compilation, compiler everytime just reloads the prepocessor state from the .PCH file while thecompiler complies other .cpp files.

    What is a Constructor?

    -> Its a non-static member function

    -> These are the functions which have the same name as that of a class.

    -> These functions are called by itself while creating an object

    -> used to initialize the data members of a class.

    -> It has no return type

    -> It can be overloaded

    -> a constructor function is not provided in a class, then C++ compiler provides a default constructor

    What is a Destrutor?

    -> This function has the same name as that of a class but starts with ~

    -> It is called by itself when object goes out of scope

    -> A destructor destroys an object

    -> used for memory cleanups, file closing and etc...

  • 8/14/2019 C++ Q2

    6/85

    -> It has no return type

    -> It cannot be overloaded

    -> It does not accept any arguments

    Example on Throw:Int Foo() throw() -> means no exception is thrown from this function

    Int Foo() throw(x,y) -> means this function will only throw exceptions x & y and exception derived from them.No other exceptions are handled.

    Int Foo() -> means that this function can throw any exception.Can I free() pointers allocated with new? ()? ------------No!Can I delete pointersallocated with malloc()? ------------No!What is a DownCast? --------------Moves a pointer down a class hierarchy, from a given class to a classderived from it.

    What is SizeOf() return?----------Returns the number of bytes occupied by the datatype.

    What does mean int **p? ----------Its an - Pointer to pointer to int OR Pointer to array of intWhy to use Void Pointer? ----------Used to cast into and back again without any loss of information.

    Where is Vtable Initialized? ------In Constructor

    What is a member Function? Its an ordinary Function- has its own name, a return type and invokedusing dot operator.

    What is a Polymorphic Class? ----Polymorphic class in any class containing a virtual function is apolymorphicWhat is a conditional Compilation? ---------are the Directives to control what does and does not getcompiled.

    Use of Scope Resolution Operator?---------used to access the base-class version from the derived

    What is a This pointer? ---------special pointer available within a class alone. Its used to refer the currentobject from within the class.

    How to delete Arrays?

    CMyObject *pobj = new CObject[128];delete [] pobj; // must

    Difference Between Copy Constructor and Assignment operator?Copy Constructor creates a new object whereas Assignment operator assigns the values to an existingobject of same class.

    Difference between Abstract and Interface ?

    Interface contains no Implementation whereas Abstract may /may-not contains implementation.

  • 8/14/2019 C++ Q2

    7/85

    How will you handle a constructor that fails?

    Throw an exception. Constructors don't have a return type, so it's not possible to use error codes.

    The best way to signal constructor failure is therefore to throw an exception.

    Why should I use new instead of trustworthy old malloc()?

    Constructors/destructors, type safety, overridability.Constructors/destructors: unlike malloc (sizeof (Fred)), new Fred () calls Fred's constructor. Similarly, deletep calls *p's destructor.Type safety: malloc () returns a void* which isn't type safe. new Fred () returns a pointer of the right type (aFred*).Overridability: new is an operator that can be overridden by a class, while malloc () is not overridable on aper-class basis.What's the difference between "const Fred* p", "Fred* const p" and "const Fred* const p"?

    You have to read pointer declarations right-to-left.* const Fred* p means "p points to a Fred that is const" -- that is, the Fred object can't be changed* Fred* const p means "p is a const pointer to a Fred" -- that is, you can change Fred object but you can't

    change pointer p itself.

    How many ways are there to initialize an int with a constant?

    int foo = 123; int bar (123);

    STLAdvantage of STL?A library of container templates approved by the ANSI committee for inclusion in the standard C++

    specification. Provides containers and algorithms that have already been written and are available in what isusually called the Standard Template Library(STL). STL provides implementation of Dynamic arrays. STLprovides a set of Template classes used to make C++ programming faster and simpler. The components ofSTL area) Algorithm b) Container c)Iterator d)Function Object d)Adaptor.What are templates?Templates are basically used to create generic classes and functions, which operates on diff data typeswithout having to overload the function or create new classes with all the possible datatypes that it issuppose to support.

    Disadvantage of using Templates?a) Compile/link time increases b) pointer manipulation problems(not freeing memory) c) Efficinecy problem

    What is MAP in STL?

    Its an Associative container.(ie map, set, multimap and multiset). It provides the ability for fast retrieval ofdatas based on keys.

    What is an Vector in STL?

    Its an Sequencial Container(ie, vector, deque, list) which organizes a finite set of objects all of same type-ina linear arrangement.

  • 8/14/2019 C++ Q2

    8/85

    What is an IteratorPointers themselves are iterators . It decouples algorithm from Container.

    What is the difference between erase() and remove() of std::list?

    Remove() removes elements by value, while erase() uses iterator for the same purpose.

    What is the difference between vector and array?

    Vectoris a one-dimensional array. It's also an STL class while array is a data type.

    What is the difference between list and vector?The major difference is the way of element access.Vectorelements may accessed randomly while list elements must be accessed sequentiallyVectoruses random access iteratorwhile list support bi-directional iterators

    Example :Vector v; v.push_back(hai);for(vector::const_iterator I= v.begin(); I != v.end(); ++I)cout handle commands and Responsible for displaying datac) Views FrameWindow ->Supports splitter window, hosts views and other controlsd) Document Template -> defines relationship among doc, view, FrameWindow

    e) Document Template Res ID -> supports Icon, Menu and String resources

    Difference between GetMessage & PeekMessage?

    Both check the message queue for a message that matches the filter criteria and then copy the message toan MSG structure. The Main Difference between 2 function is that GetMessage does not return until amessage matching the filter criteria is placed in the queue whereas Peek Message returns immediatelyregardless of whether a message is in the queue.Explain Messaging in windows?Windows is a message-based OS. It has a central message pump, which processes all the Messages thatare posted to it. Every action in windows is considered as a message. All events raised by any applicationon windows will be posted in the central message Pump as a windows message. There are 2 messages,

  • 8/14/2019 C++ Q2

    9/85

    Post message: Sends Msg to the windows messaging system and returns the control to the calling threadbefore the message is actually processed. Send message, which puts the message on the queue andwaits for a response (blocking) The message pump calls the appropriate message handler for appropriateaction to be taken on it. If no message handler is found for a message the windows default messagehandler will handle the messageExceptions in C++?

    An Expection is any unusal event either erroneous or not, detectable by either H/W or S/W, that may requirespecial processing. The special processing that may be required after the detection of an exception is calledexception handling.Try, catch and throw. If no exception is caught by Catch then Terminate() is called which in turn callsAbort()

    How will you create exception in your application?

    Using Throw statement. When Throw is executed the Try block finalizes right away and every objectcreated within the TRY block is destroyed. After that the control is passed to the corresponding Catchblock. Next, program continues right after the catch block.

    What are the Exception Classes in MFC?Cexception, CarchiveException, CdaoException, CDBException, CmemoryException, CfileException,CresourceException, ColeDispatchException, CinternetExceptionHow to catch any Exception?Catch()How will you make objects persistent in MFC?Using Serialization mechanism.Use of Carchive Class?MFC uses an object of the CArchive class as an intermediary between the object to be serialized and thestorage medium.This object is always associated with a CFile object, from which it obtains the necessaryinformation for serialization

    What is the MFC class to check Memory Leak?CmemoryState old, new, diff;old. Checkpoint ();.new. Checkpoint ();int iLeak = diff. Difference (old, new);

    What functions are used when DLL without import lib is used?

    Load Library (), GetProcAddress () and FreeLibrary().

    What are Advanced Type Cast Operators?Reinterpret-cast -> used to cast pointer between non-related classes // B*b= reinterpret _cast (a)//Static-cast -> used to cast pointer between related and fundamental data typeDynamic-cast -> used to cast pointer between polymorphism classes (Virtual function containingclasses)

    Here a check on the casting is performed at run-time .If fails returns NULLCont-cast -> used to set/Remove the constant attribute of the passed object

    What happens when you add variable or add new function in debug session? Can you continue?No. Warning New Datatype or Function are not supported by Edit&Continue. Build Required with YES andNO buttons.

  • 8/14/2019 C++ Q2

    10/85

    If YES then the Debug session is lost.How do I write to the console window?Use the fprintf() C print routine and print to a "file" called stderr. Do not use printf() for debuggingmessages! printf()buffers its messages so there is no syncronization between what you see on thegraphics screen and what you see in the text console window.

    What is a Translate Message()?

    Translate the virtual key message into character message and places it back into the Application MessageQueue

    What MFC classes that doesnt support Message Mapping ? ---------Cobject and CGDIObjectHow will you raise memory expection explicity?-------------AfxThrowMemoryException()How will you implement Message loop?Every Windows program has got a message loop The message loop, as you have noticed, consists of threemain APIs: GetMessage that pulls messages into our program, TranslateMessage that translates eachkeystroke messages to a proper character values and places it into the application's private message queue

    as WM_CHAR message, and DispatchMessage that pushes the retrieved message (msg) into the windowprocedure for processing (wndProc())MSG msg;while(GetMessage(&msg, NULL, 0, 0)){

    TranslateMessage(&msg);DispatchMessage(&msg);

    }This loop runs continuously until the reception of WM_QUIT message.What is a Device Context ?Its a Windows Data structure that contains all information about the drawing attribute of a device such as

    a display or printer. It acts as an link between the application and output device.(CDC-> CpaintDC + CclientDC) +(CgdiObjects->Cbrush,Cfont)

    How do I create a CDC from a HDC?CDC myDC;cDC.Attach(lpSomeItem->hDC); and cDC.Detach();Another approach is CDC * pDC = CDC:FromHandle(lpSomeItem->hDC);\

    How can I use a custom icon for a window?Use AfxRegisterWndClass() to register a window class with a NULL icon and then Override thePreCreateWindow()

    How can get a pointer to a control from a already created dialog?

    CButton * pButton = (CButton *)pDialog->GetDlgItem(IDC_CHECK1);

    pButton->SetCheck(m_bShowState);How do I subclass a control using MFC?

    BOOL CMyDialog::OnInitDialog(){

    m_MyControl.SubClassDlgItem(ID_MYCONTROL, this)CDialog::OnInitDialog();Ctl3dSubclassDlg(m_hWnd, CTL3D_ALL);//else it will cause assertions from multiple

    subclassing}

  • 8/14/2019 C++ Q2

    11/85

    How can you change the size of a window? -------- MoveWindow().How to work withRichEdit control?-----------------call AfxInitRichEdit() from your InitInstance()

    Threads

    A thread is a path of execution within a process. It is a unit of code that o/s can execute

    Multithreading is the ability of an program to split itself into separate threads of execution that also seemsto run concurrently.

    All threads require a thread procedure (referred to below as ThreadProc()) that subscribes to the followingfunction signature:

    DWORD WINAPI MyThreadProc(LPVOID lpvThreadParam); The address of the ThreadProc() is passed asa parameter to a CreateThread() function. The thread starts, executes the ThreadProc(), and exits. It is theprogrammer's responsibility, however, to incorporate a message loop in the ThreadProc() for retrieving anddispatching messages .

    MFC supports two types of threads: a user interface thread and a worker thread. A user interface threadcontains a Windows message loop. Unlike a user interface thread, a worker thread doesn't contain aWindows message loop, therefore no Windows-based objects can exist within it. This type of thread istypically used to perform auxiliary tasks such as querying a database.

    MFC provides the CwinThreadclass that wraps the functionality of a user interface thread. CwinApp isderived from CWinThread,

    For creating worker threads use: CWinThread* AfxBeginThread( AFX_THREADPROCpfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0,DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

    For creating user interface threads use: CWinThread* AfxBeginThread( CRuntimeClass*pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORDdwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

    In order to create a user-interface thread, you must perform the following basic steps:

    1. Create a new class, derived from CWinThread2. Implement and use the DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE macros in the newclass.3. Over ride the InitInstance in the new class.4. Call AfxBeginThread with the RUNTIME_CLASS of your new class.CWinApp is an example of a user-interface thread object, as it derives from CWinThread and handles

    events and messages generated by the user.A brief description of what AfxBeginThread does. Essentially AfxBeginThread is a helper function thathandles setting up and starting a CWinThread object for us. To do this it goes through (broadly speaking)four steps

    1.Allocate a new CWinThread object on the heap.

    2.Call CWinThread::CreateThread() setting it to initially start suspended.

    3.Set the thread's priority.

  • 8/14/2019 C++ Q2

    12/85

  • 8/14/2019 C++ Q2

    13/85

    When to Use the Synchronization Classes

    The six multithreaded classes with two categories: synchronization objects ( CsyncObject,Csemaphore, Cmutex, CCriticalSection, and CEvent) and synchronization access objects( CmultiLock and CSingleLock). CSyncObject is the base class for other four synchronizationclasses.

    Functions used (Client Side / Component Side)

    [InitializeCriticalSection(), DeleteCriticalSection() / EnterCriticalSection(),LeaveCriticalSection()]

    [CreateMutext, CloseHandle() / ReleaseMutex()][CreateSemaphore(), CloseHandle() / ReleaseSemaphore()]

    [CreateEvent(), CloseHandle() / SetEvent()]

    COM

    What is COM?

    Its an Technology. Its an Protocol used to establish communication between 2 s/w junks. Its aReusable code, which can be easily plugged and used in any language. The main benefits of COMare language independence and location transparency

    Explain the role of windows registry in case of COM.The registry stores all the details of the components that are registered in the system.

    It stores the physical path as to where the Component dll is stored in the system, so that when it isinstantiated the appropriate dll is called. It stores the DispID, CLSID, ProgID etc. necessary for a componentinstantiation.

    Diff between InProc and OutProc server in COM?Inproc: implemented as a DLL and so lives in the same address space as its client(Every client creates anew com intance)OutProc: is an executable running in its own address space on the same m/c (single com instance servicesmany client )Remote: runs on another m/c

    What's the difference between COM and DCOM?

    DCOM extends COM. DCOM introduced several improvements/optimizations for distributedenvironment, such as MULTI_QI (multiple QueryInterface()) and security contexts. DCOMdemonstrated importance of surrogate process (you cannot run in-proc server on a remotemachine. You need a surrogate process to do that.) DCOM introduced a load balancing

  • 8/14/2019 C++ Q2

    14/85

    DLL Vs COMDisAdv: Dll exposes only functions (non object oriented). Extension DLL export classes but used only fromMFC programs. DLL doesnt support Backward Compatibility(version problem). DLLs are loaded using Filename. If changed mistakenly or different vendors use same name then problem araises.Adv: Loaded Just-In-Time. Dll can share among several application. Allows application to upgrade withoutneed to recompile

    Diff between Containment and Aggregation?These are the 2 mechanism that COM provides for reuse of codeContainment : here the outer object becomes the client to inner objectAggregation: here the outer object exposes inner objects interface directly to the clients as if its a part ofouter object. (Aggregation works only among in-process component)AUTOMATIONProvides a way for objects to make function and data available to other objects. So componentscan driveone another. This is achieved using Idispatch Interface. Automation composed of 3 Parts:

    1) Automation Server // Application that expose objects2) Automation Client // Application that access objects within Automation Server3) Type Library // Provides information about objects in the Automation Server to clients at

    runtime

    ActiveX ControlsOriginallyin 1994 OCX controls were available. Later it provided initial design for OLE control. For OLE

    control to work properly on the internet ActiveX controls got resulted. ActiveX controls are reusablecomponents supporting a variety of OLE functionality. They are used for speed and efficiency. An ActiveXControl can be thought of as an Automation Server. It can be used in Scripting Languages.ActiveX controls provides User Interface. Its Self-Registering, Optimized for download and ExecuteTools to Test ActiveX Controls:1) Test Container (to check Controls functionality) 2) Control Pad (to develop Controls for web pages)MFC supports class for ActiveX controls:

    1) ColeControlModule (Derived from CwinApp) 2) ColeControl (Derived from Cwnd)3) ColePropertyPage (Derived from CDialog) 4) ColeDispatchDriverNote : the 1,2,3 are used for Creating Controls using MFC and 4 is used for making use of the

    controls

    Diff between ActiveX and DLL?

    ActiveX : Encapsulate whole aspect of object , Difficult to implement and use , used in different platformsDLL: Encapsulate only functional aspect of object, Easy to implement and use, used in Win32 platform.What is Marshalling?Involves packaging of data from the client into proxy and then unpacking it in the stub for forwarding to theserver.How automation takes place in OLE?By using Typelibrarieswwhich are imported by the Application and an Object of the Automationcomponent is created and the methods are then called for appropriate action.What is a Type library?

    Contains information about all the objects the server contains along with the interfaces and theirfunctions supported by each object. It can be read by VC++ or VB displaying the object Informationto the user. Typelib are constructed from the IDL file. (VC++5.0 ODL file was used). IDL is compiledusing MIDL compiler.

    What Interfaces must be supported for a ActiveX Component?

  • 8/14/2019 C++ Q2

    15/85

    Idispatch and IDual

    What is an Idispatch?Its an interface which allows COM to have late-binding, and therefore be used in scripting environments.Methods exposed by Idispatch?GetIDsifName() , Invoke() , GetTypeInfo() and GetTypeInfoCount()

    What is a dual interface?

    A dual inteface are simply COM interfaces that derive from Idispatch. Dual interface is one thatsupports both - IDispatch interface and vtbl-based interface. Therefore, it might be used in scriptingenvironment like VBScript and yet to use power and speed of vtbl-based interface for non-scriptingenvironment.

    What is the Advantage of server implementing as Dual Interface?It can be used from both Scripting and non-scripting Environments. Provides Fast Access if Vtables areused.

    What method gets invoked during OLE Automation Server is called? ------ GetIDsofName() andInvoke()

    What is a structured Storage?

    Structured Storage allows you to create files and organize information easily.

    Blocks of data can be placed in hierarchical form, just as files are placed in directories. Uses IStorage and IStreamInterfaces

    What is VARIANT? Why and where would you use it?

    VARIANT is a huge union containing automation type. This allows easy conversion of oneautomation type to another.

    The biggest disadvantage of VARIANT is size of the union.

    What are the different types of interfaces?

    Standard interfacesThis represents the collection ofMicrosoft developedinterfaces which are publicly documented. Standardinterfaces are also called as OLE interfaces. Ex: IShellLink, IMoniker, IPersist, IConnectionPoint, IDispatch,etc.Custom interfacesA custom interface is a user-defined interface that uses VTABLE binding(Iunknown Interface). Since aclient from a different machine may use this component, we must provide a proxy/stub DLL and theinterface identifier (IID), which must be registered before a client can communicate with our COM object.Custom interfaces do not support dynamic invocation.

  • 8/14/2019 C++ Q2

    16/85

    Automation interfacesAn Automation interface is a user-defined interface that supports dynamic invocation and late bindingvia the IDispatch interface. The advantage scripting clients can use it. Also, we dont have to createproxy/stub DLLs because Microsoft provided generic marshaling code in the Automation marshaler(oleaut32.dll). Instead of using proxy/stub DLLs, the Automation marshaler uses a type library, which storesdetailed type information regarding objects and their supported interfaces. The only disadvantage of anautomation interface is that it supports only Automation compatible data types.

    Dual interfacesA dual interface is the one which supports the IDispatch as well as VTABLE binding. IDispatch permitsdynamic invocation thereby letting even the scripting clients use your component, whereas, VTABLE permitsfaster access to the interface methods.

    One drawback of this technique is that we have to use Automation compatible types, such as BSTR andVARIANT and also all interface methods must return a HRESULT

    What is an HRESULT?

    COM component methods use HRESULTs to report error/success conditions to their users. Note thatS_FALSE is defined as 1 and S_OK is defined a 0. By convention successful return codes begin with an S_,

    while failure codes begin with an E_.

    If you have an object with two interfaces, can you custom marshal one of them?

    No! The decision is all-or-nothing; an object has to custom marshal all its interfaces or none ofthem.

    Is there a way to register in-proc server without regsvr32.exe?

    Yes. Call DllRegisterServer() & DLLUnregisterServer()

    What do you mean by Location Transparency?

    The component can be anywhere in cyberspace. For a client it doesnt matter where the component isphysically residing. This is the idea behind LocationTransparency.Location transparency is achieved using a concept called marshalling. RPC supports location transparency.COM, which is built on top of RPC supports this. To carry out communication between the client and theserver COM uses an interface to define a set of related functions defined in IDL file. Using this IDL file, MIDLcompiler will generate the marshalling code. This marshalling code is known as proxy/stub code. When aremote method invocation is made this proxy/stub code gets into action. In reality, the proxy code will

    intercept the call. The job of this code is to marshal the intelligent data into raw buffer and unmarshalls thebuffer into a data backLocation transparency offers a number of advantages.It permits Coding Flexibility by allowing us to write code that talks to a component without worrying aboutwhere the component is actually present. Provides Distribution Flexibility because objects can resideanywhere. Provides scalability. If a component is overloaded, you can add new ones to form a cluster ofcomponents. A referral component can then be built to route clients to appropriate components. It also offersfault tolerance. For example, if a particular component fails the client can be referred to a differentcomponent without the client even realizing it.

  • 8/14/2019 C++ Q2

    17/85

    About Cstring Conversions:Const Char * -> constant pointer == LPCTSTR == CString

    Char * non-constant pointer == LPTSTR (LPTSTR lp; lp= str. GetBuffer (0); and call str.ReleaseBuffer (0);)

    T2OLE (LPCTSTR str) => used to convert Cstring into OLESTRINGBSTR bs = str. AllocSysString (); and call::SysFreeString(bs);

    What is the size of BSTR?

    BSTR are length-prefixed, Null terminated OLECHAR strings.( note: olechar is a type-def to wchar_t typewhich represents 16bit Unicode characters).

    Ex: BSTR bs=hi takes 10bytes (prefix length (4)+ h(2) + i(2)+ \0(2) )What does in, outand retvalsignify when adding a method to an IDL file?Ex: HRESULT Calculate ([in] int n1, [in] int n2, [out] int *n3, [out] int *n4, [out, retval] int * z)

    A method can have any number of[in]values.A method can have any number of[out]values.The [in]parameters may or may not be pointers.The [out]parameters must always be pointers.

    A method can have only one retval.A method may not have a retvalat all.The retvalmust be the right most parameter in a method.

    Which are the different ways in which we can access the methods of a component through an MFCVC++ client?

    Method 1:CoInitialize( NULL ) ;

    hr = CLSIDFromProgID ( OLESTR ("AtlServer.Math" ), &clsid) ;hr = CoCreateInstance ( clsid, NULL, CLSCTX_ALL, __uuidof ( IMath ), ( void **)

    &math ) ;Method II: Using Smart Pointer

    IMathPtr p ;hr = p.CreateInstance (__uuidof ( Math ) ) ;

    Method III: Using Smart Pointer IMathPtr p (__uuidof ( Math ) ;Explain Security in COM?COM security relies on authentication (the process of verifying a caller's identity) and authorization (theprocess of determining whether a caller is authorized to do what it is asking to do). There are two main typesof security in COMactivation securityand call security. Activation security determines whether a client canlaunch a server at all. Once a server has been launched, you can use call security to control access to aserver's objects.

    What do you mean by object pooling?

    Object pooling is kind of recycling of objects. When a client releases an object that supports objectpooling, instead of destroying, COM+ recycles it. When another client requests same object, COM+gives an instance from recycle. Since these set of component instances

    loaded in memory so that they are immediately available for use by client applications.

    OOPS

    Define ROSE ?Rational Object Oriented Software Engineering, provides the software developer with a complete set ofvisual modeling tools for development of robust, efficient solutions to real business needs

  • 8/14/2019 C++ Q2

    18/85

    Why OOPS getting popular?

    OOPs is used to create larger programs with easier and with better quality. Used to Group related data andfunctions togetherExplain OO concepts.Polymorphism: ability of a function or operator to act in different ways on different data types is calledpolymorphism.Inheritance: Process by which objects of one class acquire properties of objects of another class.Encapsulation: wrapping up of data and functions into a single unit is known as encapsulationAbstraction: means the act of representing the essential features of something without knowing its internaldetails fully.What are Design Patterns? (RISS)So the goal of design pattern is to isolate changes in your codePatterns is used keep changes from being propagated throughout your code when you modify your code.Design patterns represents solutions to problems that arise when developing software within a particularcontext.Patterns facilitate reuse of successful software architectures and designs

    Patterns capture the static and dynamic structure and collaboration among key (Actors) participants insoftware designs.

    Pattern types:Creational Patterns -> concerns with object creation ( abstract factory, singleton)Structrual patterns -> concerned with how objects are composed off(adaptor, Bridge, Composite,Decorator, Faade, Flyweight)Behaviour Pattern -> concerned with Algorithms and responsibility between objects (Iterator,

    Mediator, Observer)What is MVC?Model (holds Business logic Beans ) View(holds GUI logic jsp) Controller(hold basic logic to processuser events servlets)Explain Each:

    Scalable : A system is said to be scalable- if as the load increases the system should still responds withinthe acceptable time.Performance: Usually measured in terms of response time for a given Screen per UserMaintainablitly: Ability to correct flaws in the existing functionality without impacting other components ofthe systemExplain OMT?(Object Modeling Techniques)OMT Involves analysis and design of a system based on 3 diff Model 1) object 2) dynamic and 3) FunctionalObject Model: Specify what objects a system contains. It shows the Static Structure and Relationshipbetween themDynamic Model : Specify when the object changes. It represents the State diagram that interact via eventsFunctional Model: Specify how objects change. Says the result without providing the Internal details usingDFD(Dataflow Diagram)Diff Between Association and Link?

    Association describes the relationship between classes. Link describes the relationship betweenobjects.Explain SOFTWARE LIFE CYCLE?Conceptualization Phase : Define Problem Statement. Generate Requirement Documentation. IdentifyUsecases holding

    happy pathAnalysis Phase : Analysis on Requirements is done. Generates Specification Document.

    Generates TestCases. Define usescase holding happy and sorrow path.Map requirement to usecase paths and classes

  • 8/14/2019 C++ Q2

    19/85

    Design Phase : Generates Design Document. Defines Data Structure, Algorithm, andProgram Structure. Error Handling Mechanism, IdentifyComponent PackagesImplementation Phase : Coding & TestingMaintenance Phase : Collect Change/ Enhancement request, which is prioritized and grouped forimplementing

    Types : WATER FALL, V, PHASED, EVOLUTIONARY, SPIRALWATERFALL -> Problem Defn Analysis Design Coding Testing MaintenanceHere each phase is considered as discrete phase. Here s/w is developed in sequential phases. There is nooverlap and the process is very straight forward. Its very difficult to accommodate changes after the processis underway

    SPIRAL -> uses prototyping model to ensure the requirements are captured correctly. Eachiteration undergoes risk analysis sector and testing sector.Define Lifecycle - describes the steps followed by the project team to produce a tangible software productDefine Process - is a documented way that contribute one/more steps in producing a productDefine Process Models ISO 9001 (applicable to all industries)

    - CMM ( applicable to software industry alone)

    Define CMM ?CMM stands for Capability Maturity Model. Software Engg Institute developed CMM for software industry.(Version 1.0 was released in 1992 and now Ver 1.1 currently available)CMM establishes a framework for performing software process Assesment and software capabilityEvaluation.Software process Assesment : focus on identifying improvements within company software processesSoftware capability Evaluation : focus on identifying risks associated with a particular project.Note: Evaluation may be performed on existing projects to monitor their process performances with theintent of identifying potential improvement with software process of the project.CMM provides a conceptual structure for improving the management and development of S/W products in adisciplined and consistent way. It does not guarantee that software products will be successfully build or thatall problems in a software process will be resolved.CMM identifies practices for a mature software processes. Note : Matured organization addresses all the

    issues essential to a successful project including People, Technology and Processes.Maturity of an organizations software process helps to project a projects ability to meet its goal.Levels of CMM INITIAL REPEATABLE DEFINED MANAGED OPTIMIZINGLEVEL 1 : Organization has no process. (Customer Req. are uncontrolled and no project managementpractices followed)LEVEL 2 : tracks the processes that fetches performance and quality (Management reacts to problemsonly when they occurs. Establishes a basic project management processes)LEVEL 3 : Organization defines the processes for execution of its day-to-day function.(Everyone andmanagement knows their roles and responsibilities. Management prepares risk management plan)LEVEL 4 : Organization defines the framework to capture and analyses the metrics. Using Metrics S/Wquality is laid. Here we quantify the quality level and processes (Management measure the progress andproblems and predict the outcome precisely)LEVEL 5 : Here the processes are continually fine-tuned to achieve still more better results as they goalong. Here inefficient activities are identified which are then replaced or revised. Here productivity andquality are improved in a controlled manner.(here we follow change management process and Technology change management processes)Define Metrics ?Measuring your progress in order to know where you are and what mid-course correction you need to taketo achieve goals.Metrics are of 2 types (1) in-process metrics and (2) end-result metrics

    Road Map to Metrics are PLAN -> DO -> CHECK -> ACT ->>>> PLAN>>>

  • 8/14/2019 C++ Q2

    20/85

    During metrics we track Time-Bound Targets and Result Oriented Targets should be measured and WeDefine the UCL and LCL and Mean-Value of a metric

    Difference between quality Control and Quality Assurance?

    Quality Control refers to testing a product after a given phase to find out if it has any defects and in case itdoes have defects to employee corrective measures to remedy the same. Quality Control is done after theproduct is build. It Oriented towards defect detection rather than defect prevention. (Ex: Testing, Test cases,Tractability matrix)

    Quality Assurance if focuses on the prevention of defect from the very start. . Its defect preventionoriented rather than defect deduction oriented. (Ex: Inspection / Review and Audits)What does SQA means?SQA S/W Quality Analyst is a person whose role is to take care of QA and QCWhat does NC means?NC: Non-Conformance are the process that escape from SQA evaluation.

    Explain Different types of TESTING ?Black Box : This is a FUNCTIONAL TEST. Needs no knowledge of internal design/code. Since tests arebased on requirements and functionality.White Box : This is a STRUCTUAL TEST . Needs knowledge of the internal design/code. Since tests arebased on coverage of code statements, conditions and paths.Unit : used to test particular function/ module. Done by programmerIncremental Integration : continious testing of an application as new functionality is added. Done by theprogrammerIntegration : testing after combining several parts of an application to determine if they function togethercorrectly.Regression : re-testing after fixes or modifications of the s/w is done.Acceptance : Final testing based on the specification of end-user , over some limited period of time. Todetemine whether the s/w is satisfactory to the customer Load : testing an application under usual heavyloads. To find out the maximum sustainable load that the system can handle .Stress : testing an application under unusal heavy loads. ( when running shortage of resource, ram, disk

    ect)Useablilty : testing the application by a thirdperson to judge the user-friendliness of the applicationCompatibility : testing how well s/w performs in a particular h/w or s/w or o/s or network ect environmentsAlpha : testing of an application when development is nearing completion .Done by end-userBeta : testing when development is completed and final bugs and problems need to be found before finalrelease. Done by end-user.

    Define UML?UML: The Unified Modeling Language (UML) is considered the de facto standard object modeling languagein the industry. The UML is the evolution of early approaches to object-oriented analysis and design. Basedon the seminal works by Grady Booch, Ivar Jacobson, and Jim Rumbaugh in the Booch, OOSE, andmethods, these three Rational experts have provided the basis for the next generation of visual softwaremodeling. The UML details the application modeling language for:

    Business process modeling with use cases

    Class and object modeling

    Component modeling

    Distribution and deployment modeling

    UML is to specify, Visualize and document the artifacts of an object oriented system under development.

  • 8/14/2019 C++ Q2

    21/85

    UML consists of

    1) modeling elements (Static and Dynamic) (static classes, attributes, relationship & dynamic-objects, Messages and state)

    2) Relationship (Dependency, Association, Generalization and Realization)3) Extensibility (Stereotype, Tagged value and Constraints)4) Diagrams (Static View and Dynamic view)

    Static View use case, component, deployment, class and object &Dynamic View sequence, collaboration, state chart and activity

    Sequence Diagram -> Time oriented, Collaboration -> Message oriented,State Chart -> Event oriented, Activity

    ->Activity oriented

    DATABASEHow do you run SQL statements from VC++?By using CDatabase class and using the method ExecuteSQL () you can run SQL Statements directly from

    VC++

    What is a Trigger?

    Trigger defines an action the database should take when some database-related events(insert/update/delete) occurs. The code within Trigger called the trigger-body is made up of PL/SQL blocks.Triggers are executed by Database.Note: When enforcing business rules first relay on declarartive referential integrity Only Use Triggers toenforce those rules that cannot be coded through referential integrity.Types of Triggers is classified based on type of triggering transaction and based on level at which triggersare executed. They are 1) Row level Triggers (triggers executed once for each row in a Tx)2) Statement

    level Triggers (triggers executed once for each Tx) 3) Before and After Triggers(inserts/updates/deletes) 4)Instead-of Triggers (redirection takes place) 5) Schema Triggers (events during create/alter/drop tables) 6)DB level Triggers (events when errors, logon, logoff, startup and shutdown). Rather can calling large blockof code within a trigger body you can save the code as a stored procedure and call the procedure fromwithin the trigger by using a call commandTo enable trigger use -> altertrigger abc enable;To enable all triggers of a table -> alter table abc enable all triggers;To disable triggers -> altertrigger abc disable /alter table abc disable all triggersTo drop triggers -> drop trigger abc;In short -Its an PL/SQL block that fires with DML command. It is not called explicitly. It is executedautomatically when the associated DML is issued. 2Types -> Row Level and Statement level TriggersExample:CREATE or REPLACE TRIGGER my_customer_audit BEFORE UPDATE On my_customer FOR EACHROWBEGIN

    INSERT INTO update_check Values('Updating a row', sysdate);END;

    Explain each:DDL -> Create , Alter, Drop, TruncateDML -> Insert, Delete, Select, Update ( all have implicit cursors)DCL (Data Control Language) -> Commit, Rollback and SavePoint

    View ->its an logical table (not a physical table). You can only insert / Delete but you cannotupdate.

  • 8/14/2019 C++ Q2

    22/85

    What class you in MFC use to connect to Database? And Connect to Tables? ---------CDatabase andCRecordSet

    Provide a SQL statement to SORT the records? ------------ORDER_BY

    DataBase Arch

    ODBC: provides ODBC driver managers and ODBC drivers. Its an low-level API used to interactwith DB.

    DAO: provides object model for DB programming. Provides Automation Interfaces, Uses JET/Access DB Engine

    RDO: developed for VB programmers. Call ODBC APIs directlyADO: Provides Automation Interface therefore used from scripting languages, Provides ObjectModel for DB programming. Here like DAO no hierarchy of objects exists.OLEDB: provides Com Interface alone. It doesnt provide Automation Interface. Used to accessboth Relational and Non-Relational databasesMFCODBC: acts as an wrapper to OBDC APIs. Its considered as high-level DB interface.

    What is Normalization?

    To eliminate data redundancy, to eleminate inconsistent dependency , actually to speedup your application,to incorporate the flexibility in the design so as to easily adopt to new changes

    What is outer join?

    Outer Joins are almost similar to Inner Joins, but in Outer Joins all the records in one table are combinedwith records in the other table even if there is no corresponding common value.

    SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.name = table2.name/

    What is a Cursor?

    When a SQL statement is executed oracle opens a private workspace area in the system called Cursor.There are 2 typesImplict Cursor(all DML statement uses) Explicit Cursor (only used by the SELECT statement whenreturning multiple records)

  • 8/14/2019 C++ Q2

    23/85

    What is the Diff between Procedure and Function?

    Both are PL/SQL named blocks used to perform a specific task . Only difference is a Procedure may or maynot return a value whereas Function must return a value. Note: Procedures:-Sophisticated Business logicand application logic can be stored as procedures within oracle. Unlike procedures, functions can return avalue to the caller.

  • 8/14/2019 C++ Q2

    24/85

    What is an Index table?

    Its based on a sorted ordering of the values. Index table provide fast access time when searching.

    Explain the Levels Normalization Process?

    First Level : Eliminate repeating of groups of data in each table by creating separate tables foreach group of related data. Identify each set of related data with a primary key

    Second Level : Releate tables using Foreign key

    Third Level : Eliminate fields/columns that do not depend on the key

    Fourth Level: in many-to- many relationship independent entites cannot be stored in the sametable (most developers ignore this rule)

    Fifth Level : the Original Table must be reconstructed from the tables into which it has beenbroken down. Its only useful when dealing with large data schema

    Zero Form : If a DB which does not complains to any of the Normalization forms. This type isusefull only for data ware housing.

    Explain Different KEYS available in DB?

    CANDIDATE KEY - an attribute that uniquely identifying a row. There can be more than onecandidate key in a table

    PRIMARY KEY - a Candidate key that you choose to identify rows uniquely is called primary key.There is only one PK for a given table.

    ALTERNATE KEY -the Candidate keys that was not choosen as primary key.

    COMPOSITE KEY: when a key is made of more than one candidate keys

    FOREIGN KEY : used to relate 2 tables using a common attribute. When a primary key in onetable is available as an attribute in another related table is called FK.

    Define Entity Integrity ?

    It ensures that each row can be uniquely identified by an attribute called the primary key whichcannot be NULL.

    Define Referential Integrity ?

  • 8/14/2019 C++ Q2

    25/85

    It ensures that all the values in the foreign key matches with the primary key values is calledreferential integrity

    Define ER Diagram ?

    Its agraphical representation of DB Structure. It has 3 things Entity (Table Name); Attribute(Column Name); and RelationShip

    Miscellaneous

    main(){

    int x=10,y=15;x=x++;y=++y;printf("%d

    %d\n",x,y);}Ans: 11 and 16

    main(){

    int x=10,y=15;int z=x++ *

    ++y;cout should be friend function

    Which of the following is the correct declaration for the function main() ?ans: main( int , char *[])if ptr is defined as int *ptr[][100]; which of the following correctly allocates memory for ptr?ans: ptr = (int *)(malloc(100* sizeof(int));

    Swapping Problem:#define swap1(a,b) a=a+b;b=a-b;a=a-b;main(){

  • 8/14/2019 C++ Q2

    26/85

    int x=5,y=10;swap1(x,y); //swap action takes placeprintf("%d %d\n",x,y);swap2(x,y); //no swap action takes placeprintf("%d %d\n",x,y);

    }int swap2(int a,int b)

    { int temp;temp=a;b=a;a=temp;return;

    }Ans : 10,5,10,5

    How do I prevent a the user from starting a second instance of my app?

    The safest way is to use a named Mutex. You can do it like this:

    BOOL CMyApp::IsAppRunning ( ){

    HANDLE hMutex = NULL;hMutex = CreateMutex ( NULL, TRUE, _T("MySpecialMutexNameHERE") );if ( GetLastError() == ERROR_ALREADY_EXISTS ){

    CloseHandle ( hMutex );return TRUE;

    }return FALSE;

    }Make sure you change the Mutex name to something unique for your app. Now, all you have to do from yourInitInstance() is :if ( IsAppRunning () ) return FALSE;The only problem with this function is that you leak the mutex handle when it does get created. It's not much

    of a problem because it will get closed by Windows when the app exits (which is what we want, anyway), butit's consider bad programming practice. For those of you more strict, here's another approach, provided byAaron J. Margosis, that uses a simple class. All you have to do is create an instance of the class when yourprogram starts and where it won't go out of scope until it exits (a member of your CWinApp-derived class willbe just fine):// Uses named mutex to guarantee a single instance with the same name on this machine. If anotherprocess has already created an instance// with the same name, "First()" will return FALSE. The object must not be destroyed until the process exits.class OnlyOne{public:

    OnlyOne( LPCSTR mutexName ): m_mutex( CreateMutex(NULL, TRUE, mutexName ) ),m_error(GetLastError() )

    {}~OnlyOne(){

    if ( m_mutex){

    CloseHandle( m_mutex );}

    }BOOL First() const{ return ( m_error == 0 ); }

    private:

  • 8/14/2019 C++ Q2

    27/85

    // These MUST be declared in this order:HANDLE m_mutex ;DWORD m_error ;

    private:// Not implemented:OnlyOne( const OnlyOne & );OnlyOne & operator = ( const OnlyOne & ) ;

    };Once again, pick a unique name for the mutex for each app you use any of the above methods in. One wayto virtually guarantee that the name will be unique is to use the textual representation of a GUID generatedfor each app, which you can use using guidgen.exe or similar tool

    How do I display a bitmap on a button?BOOL CMyDialog::OnInitDialog(){

    HWND hUpCtl;/* The button is control IDC_UP */hUpCtl = GetDlgItem( hDlg, IDC_UP );/* The icon is IDI_UP in the resource file */HICON hU = ::LoadImage( AfxGetResourceHandle(),MAKEINTRESOURCE( IDI_UP ),

    IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR );

    ::SendMessage( hUpCtl, BM_SETIMAGE, IMAGE_ICON,(LPARAM) (DWORD) hU );}How can I make the ENTER key act like the TAB key on a dialog?void CMyDlg:: OnOK(){

    CWnd *pWnd = GetFocus();ASSERT (pWnd);if (IDOK == pWnd ->GetDlgCtrlID())

    CDialog::OnOK();else

    NextDlgCtrl();}

    How can I use my VB ActiveX dll from VC++?#import "test.dll" no_namespace named_guids

    _TestPtr pTest = 0;HRESULT hres = pTest.CreateInstance ( __uuidof(Test) );pTest->TryItOut();

    How can I find the path my application or DLL was loaded from?Use The Win32 API GetModuleFileName();

    How can I shutdown the system programmatically?on NT very handy function called InitiateSystemShutdown(). It can basically do the same as ExitWindows(),except it allows you to shutdown remote systems. Remember that to do this, you need to have theSE_REMOTE_SHUTDOWN privilege granted on the remote computer, though.How do I send/post a message to the main thread from another thread?Posting or sending a user-defined message to the main thread is the best way to trigger something in the

    main thread from other threads. You start by defining the user-defined message itself. WM_APP is awindows constant that is higher than any message used by windows, so define your own windows messagelike this:

    #define MY_WM_MESSAGE1 (WM_APP + 1)Your secondary thread will need an hwnd (not a CWnd*) to post to. You can pass the main hwnd when youcreate the thread, or you can get it with AfxGetMainWnd ()->m_hWnd from within worker threads. Then youare ready to send or post a message from the secondary thread:::PostMessage(hwnd, MY_WM_MESSAGE1, (WPARAM)0, (LPARAM)0); or::SendMessage(hwnd, MY_WM_MESSAGE1,(WPARAM)0,(LPARAM)0);

    The lParam and wParam can be used to pass any parameters you like to the destination.

  • 8/14/2019 C++ Q2

    28/85

    To receive and process the message in the main thread code, first declare your message handler function inthe main window's h file. MFC does not route user-defined messages to views or docs, so the handler mustbe a member function of the CMainFrame class (or the main dialog class in a dialog-based app). Thehandlermusthave exactly this prototype:

    afx_msg LRESULT OnMyMessage1(UINT wParam, LONG lParam);The next step is to enter your message handler into the message map, typing it in manually instead of usingthe wizard. Put in an ON_MESSAGE macro like the following after the "//}}AFX_MSG_MAP" line and before

    the "END_MESSAGE_MAP()" line.//}} AFX_MSG_MAPON_MESSAGE (MY_WM_MESSAGE1, OnMyMessage1)

    END_MESSAGE_MAP ()LRESULT CMainFrame::OnMyMessage1(UINT wParam, LONG lParam){

    ... Do something about the message from secondary threadreturn 0; // I handled this message

    }

    ABOUT MFC COMThe main COM enabling MFC class is CcmdTarget. CcmdTarget is derived from Cobject class.CcmdTargetimplements Iunknown Interface.CcmdTarget handles

    1) Windows messages using Message Maps2) COM Interfaces using Interface Maps

    3) Automation using Dispatch Maps4) ActiveX controls using Event Maps

    Fundamentally all these maps work the same way. A map consists of key-value pair.Incase of Windows, message ID and pointer to message handling functionIncase of Interfaces, Interface ID and pointer to Vtable for those interfacesLets see how CcmdTarget actually work

    Ways to add interface to a class

    1) Multiple Inheritance2) Interface Implementation3) Nested Classes

    Note: MFC uses the Nested Classes by default

    Multiple Inheritance

  • 8/14/2019 C++ Q2

    29/85

    Class Cdemo: Public Iunknown, Public Idemo1, Public Idemo2{};

    Interface Implementation

    Class Cdemo : Public Iunknown{

    Cdemo1 * m_pDemo1;Cdemo2 * m_pDemo2;Friend Class Cdemo1;Friend Class Cdemo2;

    };

    Nested Classes

    Class Cdemo : Public Iunknown{

    Class Xdemo1Cls: Public Idemo1{};

    Class Xdemo2Cls: Public Idemo2

    {};

    };In MFC Nested Classes are default and its is achieved by using MFC provided macrosBEGIN_INTERFACE_PART() and END_INTERFACE_PART()

    Similarly, STDMETHOD_() macro is used to define the virtual functions.Similarly to declare interface map to a class use the following macrosDECLARE_INTERFACE_MAP()

    BEGIN_INTERFACE_MAP()INTERFACE_PART()

    END_INTERFACE_MAP()

    Ex: CDEMO.HClass Cdemo: Pulbic Iunknown{

    BEGIN_INTERFACE_PART( Demo1Cls, Idemo1)STDMETHOD_ (void, SomeFunction());

    BEGIN_INTERFACE_PART(Demo1Cls)

    BEGIN_INTERFACE_PART( Demo2Cls, Idemo2)STDMETHOD_ (void, SomeOtherFunction());

    BEGIN_INTERFACE_PART(Demo2Cls)

    DECLARE_INTERFACE_MAP(); // sets up the interface mapDECLARE_OLECREATE(Cdemo); // creates a classfactory for the com class

    };CDEMO.CPP

    #include // for guids to get initialized properlyIMPLEMENT_DYNCREATE(Cdemo, CcmdTarget) //for dynamic creationIMPLEMENT_OLECREATE(Cdemo, Demo, [provide the guid number] ) // implement classfactory//add interface mapBEGIN_INTERFACE_MAP(Cdemo, CcmdTarget)

    INTERFACE_PART(Cdemo, IID_Idemo1, DemoCls1)INTERFACE_PART(Cdemo, IID_Idemo2 DemoCls2)

    END_INTERFACE_MAP()Cdemo:: Cdemo(){

  • 8/14/2019 C++ Q2

    30/85

    AfxOleLockApp();}Cdemo:: ~Cdemo(){

    AfxOleUnLockApp();}STDMETHODIMP Cdemo:: Xdemo1Cls:: Square(Int n, LPLONG lpResult)

    { METHOD_PROLOGUE(Cdemo, Demo1Cls)lpResult = n * n;return NOERROR;

    }

    Creating CM Objects

    COM Object is identified by CLSID.The com runtime will interrogate the registry to find the server and load itif it is not already loaded . The server will then create a classfactory object whose job is to create the actualobject that implements the interface. When the object has been created, a pointer to its Vtable gets returned.MFC Implements the Iclassfactory interface in the ColeObjectFactory class.

    Explain COM Threading models?

    COM terminology to threads is slightly different. There are three types of threading models in COM. Theyare apartment threading, free threading and rental threading ( introduced for MTS ) The closest analogy toWin32 is that UI threads are analogically similar to the Apartment threading model and worker threads areanalogically similar to the Free threading model.Apartment Threading Model (single threaded apartments)This model was introduced in the first version of COM with Windows NT3.51 and later Windows 95. Theapartment model consists of a multithreaded process that contains only one COM object per thread. SingleThreaded Apartments (STA)- This also means that each thread can be called an apartment and each

    apartment is single threaded. All calls are passed through the Win32 message processing system. COMensures that these calls are synchronized. Each thread has its own apartment or execution context and atany point in time, only one thread can access this apartment. Each thread in an apartment can receive directcalls only from a thread that belongs to that apartment. The call parametes have to be marshalled betweenapartments. COM handles marshalling between apartments through Windows messaging system.

    Free Threading Model (multi threaded apartments)This model was introduced with Windows NT 4.0 and Windows95 with DCOM. The free threaded modelallows multiple threads to access a single COM object. Free threaded COM objects have to ensure threadsynchronization and they must implement message handlers which are thread aware and thread safe. Callsmay not be passed through the Win32 messaging system nor does COM synchronize the calls, since thesame method may be called from different processes simultaneously. Free threaded objects should be able

    to handle calls to their methods from other threads at any time and to handle calls from multiple threadssimultaneously. Parameters are passed directly to any thread since all free threads reside in the sameapartment. These are also called Multi-Threaded Apartments (MTA)

    Choosing the Threading Model

    Choosing the threading model for an object depends on the object's function. An object that does extensiveI/O might support free-threading to provide maximum response to clients by allowing interface calls duringI/O latency. On the other hand, an object that interacts with the user might support apartment threading tosynchronize incoming COM calls with its window operations.

  • 8/14/2019 C++ Q2

    31/85

    It is easier to support apartment threading in single-threaded apartments because COM providessynchronization on a per-call basis. Supporting free-threading is more difficult because the object mustimplement synchronization; however, response to clients may be better because synchronization can beimplemented for smaller sections of code.

    APARTMENT THREAD FREE THREAD

    Only one thread found in an apartment More than one thread found in an apartmentOne one component per thread Only one component per thread

    Owns the component it creates but doesnt share it Owns the component it creates but shared by allthreads freely

    Allows single thread to access Component Allows Multiple thread to access Component freely

    Owns a message Queue. (External calls arequeued)

    Doesnt own a message queue

    Calls are passes through the message queuesystem

    Calls doesnt pass through the message queue

    Com synchronizes the calls Com doesnt synchronizes the calls. Since freethread doesnt contain message loop

    Parameters are marshaled between apartments Not marshaled since all the free threads resides inthe same apartment

    Com need not to be thread safe. Com takes care Com must be thread safe since component must

    ensure component synchronization itselfSocketsA Socket has 3 primary components

    the interface to which it is bound (ip address)the port no: ( to which it will be sending/receiving data)the type of socket (either STREAM/ DATAGRAM)

    Socket : is an object through which window socket application Send/Receive packets of data across thenetworkPort : identifies a unique process for which a service can be provided .Certain ports are reserved forcommon services like FTP, HTTP, etc.Sockets Types:

    1) STREAM Socket ->(Sync) Bidirectional, Sequenced and Unduplicated (Ex. Telephone call)2) 2) DATAGRAM Socket ->(Async)Bidirectional,Non-Sequenced and Duplicated (BroadCasting)

    Syn waits for response // GetMessage() //BlockingAsync - Doesnt wait for response // PostMessage //Non-Blocking

    Syn1) TCP/IP protocol2) each packet has a header and footer and a sequence No: in which it has to be transferred3) each packet has to be acknowledged by the receiver. If not then the packets will be retransmitted4) its slow5) its reliable6) sequenceAsync -1) UDP packets2) encapsulate window socket APIs at low level3) used to handle Socket API directly and Dealing with N/W notification events4) here you have to handle

    a) blocking scenerios

    b) byte order diff betwn sending and receving m/csc) converting between Unicode and multibyte character set strings5) used for broadcast6)non reliable and non Sequence

    7) but Fast

    Why catch by reference?#include using namespace std;class Base{

  • 8/14/2019 C++ Q2

    32/85

    public:virtual void what(){

    cout 8 ;) -> do not create infinite loop.

    For(; ; ) and while(1) and while (!0); and for(int I=0; I creates infinite loop

  • 8/14/2019 C++ Q2

    33/85

    Comments cannot be nested (/* /* */ */ )

    Char a[] is not same as Char* a;

    Char a[5]; a= hello; is an Error. Only you have to use strcpy(a, hello);

    #pragma once -> is used to avoid multiple definations of # include files

    Do not redefine non-virtual functions down the hierarchy

    Diff between Calloc and Malloc?

    Malloc -> Takes one parameter / single block of memory is allocated / holds garbage / needstypecasting

    Calloc -> Takes two parameter / multiple blocks of memory is allocated / holds zero / needstypecasting

    Int* p = (int*)malloc(n*2) / int p =( int*)calloc(n,2)

    Diff between CallbyValue and CallbyReference ?

    CbV : here values are copied CbR : here address are copied

    Diff between While and Do-While?

    While -> first tests the codition and if true executes its statementDo-While -> First executes the statement and then tests the condition

    What are Enum and TypeDef?

    Enum is an user-defined data type that is limited to a fixed list of integer values alone. Internally compilertreats enumerated variables as integers alone. TypeDefallows to rename a datatype(both defined and userdefined datatypes)Enum A { one, two, three }; enum A a; a = one;Typedef unsigned long tl; tl var1;++a -> abc abc::Operator++() a++ -> abc abc::Operator++( int x)

    { I++; return *this; } { abc d; d= * this; I++; return d; }Book: Inside COM by Dale RogersonAll COM Interfaces must inherit from an interface named Iunknown.The purpose of vtable ?The vtable pointer adds extra level of indirection to the process of getting from an abstract base class pointer to aFunction. In COM you can access a component only through functions never directly through variables.If we create 2 different instance of CA (comp of A) then we get separate sets of instance data but share the same

    vtble and same implementation.

  • 8/14/2019 C++ Q2

    34/85

    All the classes that inherit from an interface can be treated the same way by the client. The Client can useCA and CB interchangeably through an IX pointer.Class CA : public IX {} and Class CB : public IX {} ;Void foo(IX * x){

    x->F1();

    }int main(){

    CA * pa = new CA;CB * pb = new CB;IX * x = pa;Foo(x);X= pb;Foo(x);

    }here CA and CB have separate and different instance data, vtbls and implementations.

    As long as the interface dont change the client or the component can change without breaking the entiresystem. This allows new components to replace older components without breaking the entiresystem.

    Reference counting overview

    Reference counting is a simple and fast method for enabling components to delete themselves. ACOM component maintains a number called reference count. When this reference count goes to 0the component deletes itself from memory. Ton use reference counting you have to know only 3simple rules:

    1) call AddRef before returning the interface (queryinterface and createinstance does this)2) call Release when you are done.3) Call AddRef whenever you assign an interface pointer to another interface pointer.

  • 8/14/2019 C++ Q2

    35/85

    COM Library has to be initialized only once per process by calling CoInitialize. If it has been called for aprocess already then it will return S_FALSE instead of S_OK. Since it has to initialized only once perprocess and COM Library is used to create components in-proc components dont need to initialize thelibrary. The general convention is to handle COM initialization in EXEs and not in DLLs. A Coinitialize has topaired with counintialize.OLE is build on top on COM. OLE Library contains extra support . Ole is called by using oleinitialize and

    oleunintialize. The ole* function calls internally Co* functions. However using ole* instead of Co* wastesresources and time . In DCOM use CoInitializeEx to mark a component as Free-Threaded.CoCreateInstance functions inflexibility:

    Objects must be created before they can be used. If objects creation is different for every object it becomesharder to use different objects polymorphically. Therefore we want object creation to be as flexible aspossible so that all components can be created in a similar manner. When cocreateinstance method call isfinished the component is already created which is too late to put conditions on its creation. The solution tothis is to make explicit use of another component whose sole purpose is to create component we want. Nowhere comes the classfactory concept.

    Behind the scences cocreateinstance creates a component called classfactory which then creates desiredcomponents. The client uses IclassFactory for controlling how the classfactory creates each component.

    Cocreateinstance takes a CLSID and returns a pointer to an interface in a componentClassfactory takes a CLSID and returns a pointer to an interface in the class factory.To this we use CoGetClassObject which returns the requested pointer to the class factory whilecocreateinstance returns pointer to the component itself. CoCreateInstance takes an Iunknown pointer whileCoGetClassObject takes a COSERVERINFO pointer(which is used by DCOM to control remotecomponents)Note: There is another interface IclassFactory2 which adds licensing or permissions to IclassFactory. Usingthis classfactory can ensure that client is authorized to use the component.CoCreateInstance is actually implemented using CoGetClassObject.CocreateInstance(, void** ppv){IclassFactory * pFactory = NULL;

    CoGetClassObject(,(void **)&pFactory);pFactory ->CreateInstance(,ppv);}

    There are 2 cases in which CoGetClassObject should be used instead of CoCreateInstance.1) whenever you want to use IclassFactory22) whenever you want to create a bunch of components all at one timeUsing Classfactories is much more confusing than letting CoCreateInstance do the work for youNote : CoGetClassObject calls the function DllGetClassObject which actually creates class factory.

    // 3- creates ClassFactory & 6- creates Component //

  • 8/14/2019 C++ Q2

    36/85

    First the client calls CoCreateInstance which is implemented in the COM Library. CoCreateInstance isimplemented using CoGetClassObject which actually looks the component in the registry.If it finds thecomponent it loads the DLL that serves the component. After the DLL loads CoGetClassObject callDllGetClassObject. DllGetClassObjectis implemented in the DLL Server. Its job is to create the classfactoryand it also queries the class factory for IclassFactory interface which is returned to CoCreateInstance. TheCoCreateInstance then uses the IclassFactory interface to call its CreateInstance function.CoCreateInstance releases the classfactory and returns the IX pointer to the client .The client can then use

    the interface pointer to call a method on the component.COM does not support implementation inheritance because implementation inheritance binds one objecttightly to the implementation inheritance of another object. If the implementation of a base object changesthe derived objects break and must be changed.

    What is a smart pointer?A smart pointer is a class that overrides operator ->. The smart pointer class contains pointer to anotherobject. They delegates the call to the object pointed to by the contained pointer. Smart pointer is a smartpointer that contains a pointer to an interfaceCoolest thing about smart pointer is that we dont have to remember to call Release. When the smart pointergoes out of scope it automatically calls Release in its destructor. You shouldnt call Release on the smartpointer. Only you should should assign the pointer to NULL. (spIx = NULL;)

    Why do we need to cross the process boundry?

    If your application is already an EXE then you have to implement components as EXEs insteadof DLLs. Every EXE runs in a different process.The logical address in one process access a differentphysical memory location.If a component is in a DLL your client can easily access the memory because the component and the clientare in the same address space. But if the client and component are in different address spaces the clientcant access the memory in the components process. If client cant access then our interfaces would bepretty useless. There are many options for communicating between processes including DDX, named pipesand shared memory. However COM uses LPC. LPCs are a means of communication between differentprocesses on the same machine. LPCs are implemented by the operating system and it knowns how tohandle it. IF both the processes are on the same machine marshalling is fairly straight forward. The data inone process needs to be copied to the address space of another process. If the processes are on differentmachines the data has to be put into to a standard format fro the differences between machines.To marshal a component implement an interface named Imarshal. The main reason for this is to improve

    performance.If the client to communicate with in-proc,local and remote components worry about LPCs then the goal oflocal transperancy is lost. COM achieves this by using Proxy/Stub dlls. The MIDL compiler takes IDL file andgeneratesC-Code for the proxy and stub DLL.FOO.H -> contains declarations of all the interfaces described by IDL file (Interfacedeclaration)FOO_I.C -> defines all the GUIDs used in the IDL file. (InterfaceGUIDs)FOO_P.C -> implements the proxy and stub code for the interfaces in the IDL file(Proxy/ Stub Dlls)DLLDATA.C -> implements the DLL that contains the proxy and stub code. ( Dll Code)

    Idispatch

    Automation focuses on run-time type checking and compile-time type checking. An automationserver is a cOM component that implements Idispatch interface. An Automation controller doesnt directlycall the functions implemented by the automation server.Instead it uses the member functions in theIdispatch interface to indirectly call functions in the automation server.A DISPID is not a GUID but just a long integer . The DISPID identifies a function. Automation controllerpasses DISPID to invoke member function. The invoke function can use DISPID as an index in an array offunction pointers.A set of functions implemented by an Idispatch::Invoke() implementation is called a dispatch interface orDispinterface for a short. Dispinterface contains an array of function names and an array of functionpointers indexed by DISPIDs.

  • 8/14/2019 C++ Q2

    37/85

    Its a COM interface that implements Idispatch::Invoke inherit from Idispatch instead ofIunknown. A Dual interface is a dispinterface that makes all the functions that are available through Invokealso available directly through the Vtbl . Dual Interfaces allow C++ programmers to make their calls via theVtbl ; such calls not only are easier for C++ programmers to implement but executes faster. Instead ofcalling through the vtble scripting languages can call via the invoke method. A VB program can eitherconnect to dispinterface part or vtbl part of a dual interface.

    TypeLibrary

    The compiler ensures at compile time that the correct argument types are passed to each

    function using the header file. But, We have not provided VB with an equivalent to the C++ header file. Onlythe VARIANT structure make this possible. You can resolve this by replacing C++ header file withTypelibrary. VB doesnt require a header file it uses VARIANT which allows us to almost completely removestatic type checking in favour of having the component check types at runtime but its very time consumingand also lead to program errors. Therefore we need a language equivalent of C++ header files . The solutionin COM is typelibraries, which provide type information about components , interfaces, methods, properties,arguments and structures. The content of a typelibrary is the same as that of a C++ header file. Atypelibrary can be accessed programmatically. Its an Binary file. Without typelibrary VB is limited tocommunicating to components through DispInterfaces. If a typelibrary is available VB can accesscomponent through Vtbl part of its dual interface. Access through Vtbl is typesafe and faster.To create type library use automation library function CreateTypeLib which returns IcreateTypeLib interfacewhich is used to fill the type library information. IDL and MIDL compilers are used to build type libraries.To use type library use LoadRegTypeLib which attempts to load type library from the windows registry . Ifyou use LoadTypeLib is loads from disk.

    Interfaces accessible through vtbl (called from c++ programs)

  • 8/14/2019 C++ Q2

    38/85

  • 8/14/2019 C++ Q2

    39/85

    is that all messages are synchronized. Windows are guranteed to get messages in the proper order. Writingthread-safe code is very time consuming.COM instead of calling user-interface thread uses the term apartment thread. The term free thread isused instead of worker thread. An apartment is a conceptual entity consisting of a user-interface stylethread and a message loop.Note : In-proc components dont have their own message loops but instead share the message loop oftheir client EXE.

    The Out-of-proc server for the component provides it with a message loop.

    Apartments are similar to Single threaded processes in all the foll aspects:A process has its own message loop. An apartment has its own message loop. Function calls within aprocess and function calls within an apartment are not marshaled. Synchronization of function calls acrossprocesses or across apartment boundaries is performed through the message loop. As a final detail, eachprocess must initialize the COM library. Likewise each apartment must initialize the COM library

    Process Boundary

    Marshalling takes place

    CoUnInitialize

    Client

    CoInitializeCoInitialize

    Component

    Component

  • 8/14/2019 C++ Q2

    40/85

    Apartment Boundaries

    An Apartment thread is one and only thread found in an apartment. An apartment thread owns thecomponent component it creates. A component in an apartment will be called only by the apartment thread.If the thread send a message to a window owned by a different thread, windows places the message intothe message queue for the window. If another thread calls a method on our component which is in anapartment the COM places the call into the queue for the apartment. The message loop pulls the call off andcalls the method on the apartment thread.

    Free Threaded

    COM Synchronizes calls to components on apartment threads. COM doesnt synchronize calls tocomponents created by FreeThreads. If a component is created by a free thread it can be called by anythread and at any time. The developer of the component must ensure that the component synchronizesaccess to itself.The component must be thread safe. Free threading moves the burden of synchronization

    from COM to the component.Since COM doesnt synchronizes calls to component, free threads dont needmessage loops. A component created by a free thread is considered as a free thread component. Thecomponent is owned by the thread that created it but is sharing among all threads can be accessed freely beall threads.Note: A apartment thread is similar to win32 process in that both have a single thread and a message loop.A single process can have any number of apartment threads and free threads. Only the thread that created itmust call a Component created in an apartment thread.

    Which type of thread should you use?

    User-interface code must use apartment threads. If you need only to perform a simple operation inbackground use free threads. They are much easier to implement. Moreover all calls to an apartment thread

    must be marshaled .This can be a significant performance hit.Calls between free threads in the sameprocess are not marshaled and can be much faster, depending on how the component implement theirsynchronization code.DNA: - Ideal to design and implement robust distributed application Providing Client Transparency and FaultTolerance. It takes care of plumbing work to connect separate parts to work together. It provides full Txprocessing supportFault Tolerance - no N/W is guaranteed to give continuous and fast performance. Therefore it provides away to cope with N/W delays and S/W failures while protecting the data integrity.What does component support binary compatibility means?We dont have to unregistered and register the control every time we compile it again and again. Means the

    CLSID and IID remains same for new builds of the component each time.

    MTS: - Its a service available to the client in the background providing support to Manage bothComponent and Tx. It also provides service to applications that dont use Tx. As a service itallocates, activates, deactivates instance of component that are used by your application. This canimprove response time and resource availability. As a Tx Processor allows to build a reliable androbust data management application much simpler, especially in distributed application where thedata resides on different / remote servers.

    MTS can be managed using Tx Server Explorer and in NT we call MMG (Microsoft ManagementConsole)

    CoUnInitialize

  • 8/14/2019 C++ Q2

    41/85

    In WinNT add reference to MTS Type Library to VB Project whereas in Win2k use COM+ service typelibrary.

    Explain MTS Context ?

    Component Creation and Destruction problem is solved by providing a pool of component instances likeconnection pooling. MTS can provide a component to an application on demand and allow other applicationto