Thursday, March 5, 2009

C++ Interview Questions & Answers

Q: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?
A: There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor
is a code which is responsible for creating an instance of a class and it can’t be delegated to
any other object by virtual keyword means.

Q: What is constructor or ctor?
A: Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is
different from other methods in a class.

Q: What about Virtual Destructor?
A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime
depending on the type of object caller is calling to, proper destructor will be called.

Q: What is the difference between a copy constructor and an overloaded assignment operator?
A: A copy constructor constructs a new object by using the content of the argument object. An
overloaded assignment operator assigns the contents of an existing object to another existing
object of the same class.

Q: Can a constructor throws an exception? How to handle the error when the constructor fails?
A:The constructor never throws an error.

Q: What is default constructor?
A: Constructor with no arguments or all the arguments has default values.

Q: What is copy constructor?
A: Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you. for example:
(a) Boo Obj1(10); // calling Boo constructor
(b) Boo Obj2(Obj1); // calling boo copy constructor
(c) Boo Obj2 = Obj1;// calling boo copy constructor

Q: When are copy constructors called?
A: Copy constructors are called in following cases:
(a) when a function returns an object of that
class by value
(b) when the object of that class is passed by
value as an argument to a function
(c) when you construct an object based on another
object of the same class
(d) When compiler generates a temporary object

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference
of the object?
A: No. It is specified in the definition of the copy constructor itself. It should generate an error if
a programmer specifies a copy constructor with a first argument that is an object and not a
reference.

Q: What is conversion constructor?
A: constructor with a single argument makes that constructor as conversion ctor and it can be
used for type conversion.
for example:
class Boo
{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object

Q:What is conversion operator??
A:class can have a public method for specific data type conversions.
for example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double.
now conversion operator gets called to assign the value.

Q: How can I handle a constructor that fails?
A: throw an exception. Constructors don't have a return type, so it's not possible to use return
codes. The best way to signal constructor failure is therefore to throw an exception.

Q: How can I handle a destructor that fails?
A: Write a message to a log-_le. But do not throw an exception. The C++ rule is that you must
never throw an exception from a destructor that is being called during the "stack unwinding"
process of another exception. For example, if someone says throw Foo(), the stack will be
unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get
popped. This is called stack unwinding. During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a
Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up
in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a }
catch (Bare) { handler? There is no good answer:either choice loses information. So the C++ language guarantees that it will call terminate() at this point, and
terminate() kills the process. Bang you're dead.

Tuesday, March 3, 2009

Part - 4 MFC Interview Questions & Answers

Q:- What is socket?
Ans:- A "socket" is an endpoint of communication: an object through which your application communicates with other Windows Sockets applications across a network.The two MFC Windows Sockets programming models are supported by the following classes: CAsyncSocket and CSocket

Q:- What is the difference between Synchronous sockets and asynchronous sockets?
Ans:- Consider a server application that is listening on a specific port to get data from clients. In synchronous receiving, while the server is waiting to receive data from a client, if the stream is empty the main thread will block until the request for data is satisfied. Hence, the server cannot do anything else until it receives data from the client. If another client attempts to connect to the server at that time, the server cannot process that request because it is blocked on the first client. This behavior is not acceptable for a real-world application where we need to support multiple clients at the same time. 

In asynchronous communication, while the server is listening or receiving data from a client, it can still process connection requests from other clients as well as receive data from those clients. When a server is receiving asynchronously, a separate thread (at the OS level) listens on the socket and will invoke a callback function when a socket event occurs. This callback function in turn will respond and process that socket event.

Q:- Have you ever used win32 APIs ?
Ans:- MFC is a wrapper around win32 API, It provides classes which uses the win32 API, Some of the API's we usually work with are : GetDlgItemInt,GetDlgItemText,GetWindowTextA,Messag eBoxA,CreateFile,CreateMutex,CreateEvent,WaitForSi ngleObject,CreateWindow,ShowWindow etc.,

Q:- What is the difference between ANSI Code and UNICODE ?
Ans:- ANSI code represents 8bytes data where UNICODE represents 16bytes data for supporting universal languages. One major draw back to ASCII was you could only have 256 different characters. However, languages such as Japanese and Arabic have thousands of characters. Thus ASCII would not work in these situations. The result was Unicode which allowed for up to 65,536 different character

Q:- What is the difference between regular dlls and extended dlls?
Ans:- Regular dlls wraps only the c/c++ functions. Where extention dlls include c++ interfaces where we can create the objects of it and use in our classes. Extended dlls support object oriented concepts.Regural dlls uses mfc internally and exported functions can be used by any mfc or non-mfc applications.Extention dlls implements reusable classes derived from mfc library,built using dll version of mfc.Only mfc executables(applications/dll-shared version of mfc) can use extention dlls.extention dlls used for passing mfc derived objects b/w applications and dlls. Regulardlls linked both statically and dynamically but extended dlls links dynamically.

Q:- What is a message map, and what is the advantage of a message map over virtual function ?
Ans:- MessageMap is a logical table that maps the windows messages to the member functions of the class. We use message maps over virtual function because of lots of overhead. If every windows message had a virtual function associated with it , there would be several hundred bytes per window class of vtable. Message maps means we only pay for the messages we use.

Q:- Given two processes, how can they share memory?
Ans:- Processes and thread are very similar but they differ in the way they share their resources. Processes are independent and have its own address space. If two independent processes want to communicate they do this by using the following techniques 1.Message Passing 2.Sockets 3. named pipes
Or
Use memory-mapped files to share data memory between processes

Q:- How to restrict only one instance of a class object to be created?
Ans:- Create a Named Mutex.
HANDLE hMutex=CreateMutex(TRUE,_T(“NamedMutex”))
And check the Mutex existence for each of your instance launch and dont allow it to launch if it exists.

Q:- How do I dynamically change the mainframe menu?
Ans:- CMenu newMenu;
newMenu.LoadMenu (IDR_MENU1);
AfxGetMainWnd()->SetMenu( &newMenu );
AfxGetMainWnd()->DrawMenuBar();
newMenu.Detach ();

Monday, March 2, 2009

Part - 3 MFC Interview Questions & Answers

Q:- What is model and modeless dialog box ? Give some examples?
Ans:- When we create Modal Dialog Box we can't move to other windows until this dialog is closed. For eg: MessageBox, where we can't move to the other window until we press ok or cancel. 
When we create Modeless Dilaog Box we can swap to the other windows. For eg: like a conventional window.

Q:- How to create open & save dialogs ?
Ans:- In CommonDialogs class we have to use CFileDialog class where the first parameter TRUE for open dialog and FALSE for Save dialog.
For file open:
CFileDialog SampleDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,"Text Files (*.txt)|*.txt|Comma Separated Values(*.csv)|*.csv||");

int iRet = SampleDlg.DoModal();

Q:- What is CSingleDocTemplate?
Ans:- It’s a document template class used to create single document interface SDI applications. Only one document can be opened at a time. It identifies the document class used to manage the application's data, the frame window class that encloses views of that data, and the view class used to draw visual representations of the data. The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.

Q:- What is the difference between hinstance and hprevinstance in WinMain function?
Ans:- hInstance is used for things like loading resources and any other task which is performed on a per-module basis. A module is either the EXE or a DLL loaded into your program. hPrevInstance used to be the handle to the previously run instance of your program (if any) in Win16. It is always NULL for Win32 programs.

Q:- Explain about MDI and CMultiDocTemplate ?
Ans:- MDI applications are designed using the doc-view architectures in which there could be many views associated with a single document object and an application can open multiple docuements at the same time for eg:WORD.
In MDI terms, your main window is called the Frame, this is probably the only window you would have in a SDI (Single Document Interface) program. In MDI there is an additional window, called the MDI Client Window which is a child of your Frame window. CMultiDocTemplate is the document template class used to create MDI applications..The document template also stores a resource ID that the framework uses to load menus, accelerators, and other resources that shape the application's user interface.

Q:- Which are the different controls in MFC ?
Ans:- CAnimateCtrl, CButton, CEdit, CListBox, CComboBox, CRichEditCtrl, CStatic, TreeCtrl, ToolTipCtrl, IPAddressCtrl, TabCtrl,CDa teTimeCtrl, HeaderCtrl, ListCtrl, MonthCalCtrl, OleCtrl, ProgressCtrl, ScrollBar, SliderCtrl, StatusBarCtrl, TollBarCtrl etc.,

Q:- What is the use of OnInitDialog ?
Ans:- This message is sent to the dialog box during the Create, CreateIndirect, or DoModal calls, which occur immediately before the dialog box is displayed. This can be used to intialize the dialog controls or show/hide the controls etc.,

Q:- What is the functioning of UpdateData() funciton ?
Ans:- This is to initialize data in a dialog box, or to retrieve and validate dialog data.
The framework automatically calls UpdateData with bSaveAndValidate set to FALSE when a modal dialog box is created in the default implementation of CDialog::OnInitDialog. The call occurs before the dialog box is visible. The default implementation of CDialog::OnOK calls this member function with bSaveAndValidate set to TRUE to retrieve the data, and if successful, will close the dialog box. If the Cancel button is clicked in the dialog box, the dialog box is closed without the data being retrieved.

Q:- How to update all the views whenever document got updated ?
Ans:- call UpdateAllViews()- which updates all views associated with the document by calling OnUpdate() function of all the views.

Q:- How to handle RTTI in MFC ?
Ans:- Run-Time Type Information is a mechanism that allows the type of an object to be determined during the program execution. 3 main elements to RTTI in MFC are
1. Dynamic_cast operator Used for conversion of polymorphic types.
2. typeid - used for identifying the exact type of an object 
3. type_info classused to hold the type information returned by typeid.

Q:- What is serialization ?which function is responsible for serializing data ?
Ans:- Searialization is the process of streaming the object data to or from a persistent storage medium. It's useful in Doc-View Architecture. CObject :: Serialize() function is used to do serialization.

Q:- what is the use of Mutex and critical section ?
Ans:- Mutex as the name suggest allows a mutullay exclusive access to a shared resource among the threads. Critical section is a piece of code that can be executed safely to be accessed by two or more threads. Criticalsection provides synchronization means for one process only, while mutexes allow data synchronization across processes. Means two or more threads can share the common resources among more than one application or process boundaries in mutex.

© All Content is Under Copyright Protection © 2008-2009 VC++ Interview Tips | Site Best Viewed in Firefox