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.

Saturday, February 28, 2009

Part - 2 MFC Interview Questions & Answers

Q:- What is thread & process?
Ans:- Threads are similar to processes, but differ in the way that they share resources. Threads are distinguished from processes in that processes are typically independent, carry considerable state information and have separate address spaces. Threads typically share the memory belonging to their parent process.

Q:- what is the use of AFX_MANAGE_STATE ?
Ans:- By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope. If all your resources lies in the single DLL you can even change the default handle to the DLL handle with the help of AfxSetResourceHandle function.

Q:- Why wizards generate enum IDD for dialogs?
Ans:- It's good programming practice to do it this way, as from the client code you can always refer to the CMyDlg::IDD without worrying what the actual constant is.

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

Q:- How to handle command line arguements from simple MFC application ?
Ans:- m_lpCmdLine Corresponds to the lpCmdLine parameter passed by Windows to WinMain. Points to a null-terminated string that specifies the command line for the application. Use m_lpCmdLine to access any command-line arguments the user entered when the application was started. m_lpCmdLine is a public variable of type LPTSTR.
BOOL CMyApp::InitInstance()
{
// ...
if (m_lpCmdLine[0] == _T('\0'))
{
// Create a new (empty) document.
OnFileNew();
}
else
{
// Open a file passed as the first command line parameter.
OpenDocumentFile(m_lpCmdLine);
}
// ...
}

Q:- What is the base class for MFC Framework ?
Ans:-CObject

Q:- If I derive a new class from CObject what are the basic features my derived will get?
Ans:-Searialization, Debugging support, Runtime time class information, compatibility with collection classes.

Q:- What is the use of CCmdTarget ?
Ans:- It is the base class for the MFC library message map architecture.Which maps commands/messages to the member functions to handle them. Classes derived from this are CWnd,CWinApp,CFrameWnd,CView, CDocument

Q:- What is document-view architecture ? Give me one real time example for SDI ?
Ans:- Document/view architecture, which defines a program structure that relies on document objects to hold an application's data and on view objects to render views of that data. MFC provides the infrastructure for documents and views in the classes CDocument and CView. example of SDI is a wordpad application

Q:- Can you explain the relashionship between document,frame and view ?
Ans:- The frame window is the application's top-level window. It's normally a WS_OVERLAPPEDWINDOW-style window with a resizing border, a title bar, a system menu, and minimize, maximize, and close buttons. 
The view is a child window sized to fit the frame window so that it becomes the frame window's client area. 
The application's data is stored in the document object, a visible representation of which appears in the view. 
For an SDI application, the frame window class is derived from CFrameWnd, the document class is derived from CDocument, and the view class is derived from CView or a related class such as CScrollView.

Q:- How to access document object from view ?
Ans:- Using GetDocument() function within a CView class.

Q:- What is the entry point for window based applications ?
Ans:- WinMain() is the entry point for window based applications.

Q:- Explain the flow for a simple win32 based application ?
Ans:- Starting point for win32 based applications is WinMain()
WinMain begins by calling the API function RegisterClass to register a window class. The window class(WNDCLASS) defines important characteristics of a window such as its window procedure address, its default background color, and its icon. Once the WNDCLASS is registered, WinMain calls the all-important CreateWindow function to create the application's window. WinMain follows CreateWindow with calls to ShowWindow and UpdateWindow, which make the window visible and ensure that its WM_PAINT handler is called immediately. Next comes the message loop. In order to retrieve and dispatch messages, WinMain executes a simple while loop that calls the GetMessage, TranslateMessage, and DispatchMessage API functions repeatedly. GetMessage checks the message queue. If a message is available, it is removed from the queue and copied to msg; TranslateMessage converts a keyboard message denoting a character key to an easier-to-use WM_CHAR message, and DispatchMessage dispatches the message to the window procedure. The message loop executes until GetMessage returns 0, which happens only when a WM_QUIT message is retrieved from the message queue. When this occurs, WinMain ends and the program terminates.

MFC Interview Questions & Answers

Que: What is the difference between GetMessage and PeekMessage ?
Ans: GetMessage function waits for a message to be placed in the queue before returning where as PeekMessage function does not wait for a message to be placed in the queue before returning.

Que: What’s the difference between PostMessage and SendMessage?
Ans: The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and then returns without waiting for the thread to process the message.

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

Que: How to create a model less dialog?
Ans: m_pModeless is a variable of type CDialog or any of its descendants.
m_pModeless->Create(IDD_DIALOG1, this);
m_pModeless->ShowWindow(SW_SHOW); 
this pointer as a paramter suggest we are creating a child dialog of the current dialog/window.

Que: How to setup a timer?
Ans: Use the SetTimer function
UINT_PTR SetTimer( HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, 
TIMERPROC lpTimerFunc );
To kill the timer use
BOOL KillTimer(int nIDEvent);
Where the nIDEvent is the ID returned by the SetTimer Function.

Que: Name the Synchronization objects ?
Ans: Following are the synchronization objects 
1) Critical Section 2) Event 3) Mutex 4) Semaphore
Classes provided for above synchronization objects are:
1) CCriticalSection 2) CEvent 3) CMutex 4) CSemaphore

Que: What Is CMutex ?
Ans: An object of class CMutex represents a “mutex” — a synchronization object that allows one thread mutually exclusive access to a resource. Mutexes are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CMutex object to control the linked list, only one thread at a time can gain access to the list.
To use a CMutex object, construct the CMutex object when it is needed. Specify the name of the mutex you wish to wait on, and that your application should initially own it. You can then access the mutex when the constructor returns. Call CSyncObject::Unlock when you are done accessing the controlled resource.

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

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

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

Que: what is the use of AFX_MANAGE_STATE ?
Ans: By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope. If all your resources lies in the single DLL you can even change the default handle to the DLL handle with the help of AfxSetResourceHandle function.

Friday, February 13, 2009

C Inteview Question

Question :: Read below code and answer the following questions.

 

LINE

Contains

50

char * b, q, *r;

200

b=getbuf();

201

q = *b;

212

r= anotherfunction(b);

213-300

/* we want to use ‘q’ and  ‘r’ here*/

2000

char * getbuf()

2001

{

2002

   char buff[8];

2003-2050

/* unspecified, buff defined here *./

2051

  return (char *) buff;

2052

}




1. What will be in variable ‘q’ after line 201 is executed? Under what conditions might this not be so?
Answer:


2. Is there an alternative, but equivalent, way to write line 2000? If so, what is it?
Answer:



3. Is getbuf() a reasonable function?
Answer:



4. Will getbuf() execute at all?
Answer:



5. Please comment on line 2051.
Answer:



6. Is getbuf() good practice, and why?
Answer:



7. What line not given should be provided for compilation?
Answer :



(Suggestions and comments are welcome)

Wednesday, February 11, 2009

Interview FAQs : C++ (Answers End of Post)

1) Which is the parameter that is added to every non-static member function when it is called?
---------------------------------------------------------------------------------------
2)
class base
{
public:
int bval;
base(){ bval=0;}
};
class deri:public base
{
public:
int dval;
deri(){ dval=1;}
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i <>bval;
cout << endl; } int main() { base BaseArr[5]; SomeFunc(BaseArr,5); deri DeriArr[5]; SomeFunc(DeriArr,5); }
---------------------------------------------------------------------------------------
3)
class base { public: void baseFun(){ cout << "from base" <<>baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
Deri deriObject;
SomeFunc(&deriObject);
}
---------------------------------------------------------------------------------------
4)
class base
{
public:
virtual void baseFun(){ cout << "from base" <<>baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
Deri deriObject;
SomeFunc(&deriObject);
}
---------------------------------------------------------------------------------------
5)
class some
{
public:
~some()
{
cout << "some's destructor" << endl; } }; void main() { some s; s.~some(); } ---------------------------------------------------------------------------------------
6) #include class fig2d { int dim1; int dim2; public: fig2d() { dim1=5; dim2=6;} virtual void operator<<(ostream & rhs); }; void fig2d::operator<<(ostream &rhs) { rhs <<>dim1 <<" "<<<" "; } /*class fig3d : public fig2d { int dim3; public: fig3d() { dim3=7;} virtual void operator << (ostream &rhs); }; void fig3d::operator << (ostream &rhs) { fig2d::operator <<(rhs); rhs <<>dim3;
}
*/

void main()
{
fig2d obj1;
// fig3d obj2;
obj1 << cout; // obj2 << cout; }
---------------------------------------------------------------------------------------
7) Class opOverload { Public: bool operator==(opOverload temp); }; bool opOverload::operator==(opOverload temp) { if(*this == temp ) { cout << "The both are same objects\n"; return true; } else { cout << "The both are different\n"; return false; } } void main() { opOverload a1, a2; a1= =a2; }
---------------------------------------------------------------------------------------
8) Class complex { double re; double im; public: complex() : re(1),im(0.5) {} bool operator==(complex &rhs); operator int(){} }; bool complex::operator == (complex &rhs) { if((this->re == rhs.re) && (this->im == rhs.im))
return true;
else
return false;
}
int main()
{
complex c1;
cout << c1;
}
---------------------------------------------------------------------------------------
9)
Class complex
{
double re;
double im;
public:
complex() : re(0),im(0) {}
complex(double n) { re=n,im=n;};
complex(int m,int n) { re=m,im=n;}
void print() { cout << re; cout << im;}
};
void main()
{
complex c3;
double i=5;
c3 = i;
c3.print();
}
---------------------------------------------------------------------------------------
C++ Answer
---------------------------------------------------------------------------------------
1. ‘this’ pointer

00000

2. 01010

3. from base
from base

4. from base
from Derived

5. some's destructor
some's destructor

6. 5 6

7. Runtime Error: Stack Overflow

8. Garbage value

9. 5,5

Interview FAQs : C (Answers at end of post)

1. Base class has some virtual method and derived class has a method with the same name. If we initialize the base class pointer with derived
object, Calling of that virtual method will result in which method being called?

a. Base method
b. Derived method...
-----------------------------------------------------------------------------------------------
2. For the following C program

#define AREA(x)(3.14*x*x)
main()
{float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}

What is the output?
-----------------------------------------------------------------------------------------------
3.
void main()
{
int d=5;
printf("%f",d);
}
-----------------------------------------------------------------------------------------------
4.
void main()
{
int i;
for(i=1;i<4,i++) s="\12345s\n" i="1;" k=" -1"> k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(ij)
printf("greater");
else
if(i==j)
printf("equal");
}
-----------------------------------------------------------------------------------------------
5.
void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}
-----------------------------------------------------------------------------------------------
6.
void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(ij)
printf("greater");
else
if(i==j)
printf("equal");
}
-----------------------------------------------------------------------------------------------
7.
void main()
{
float j;
j=1000*1000;
printf("%f",j);
}

1. 1000000
2. Overflow
3. Error
4. None
-----------------------------------------------------------------------------------------------
8. How do you declare an array of N pointers to functions returning
pointers to functions returning pointers to characters?
-----------------------------------------------------------------------------------------------
9.
int f()
void main()
{
f(1);
f(1,2);
f(1,2,3);
}
f(int i,int j,int k)
{
printf("%d %d %d",i,j,k);
}

What are the number of syntax errors in the above?
-----------------------------------------------------------------------------------------------
10.
void main()
{
int i=7;
printf("%d",i++*i++);
}
-----------------------------------------------------------------------------------------------
11.
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
-----------------------------------------------------------------------------------------------
12.
void main()
{
int count=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}

-----------------------------------------------------------------------------------------------
13. what is alloca()
-----------------------------------------------------------------------------------------------
14.
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
-----------------------------------------------------------------------------------------------
15.
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}
-----------------------------------------------------------------------------------------------
16.
void main()
{
char *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s",++*p);
printf("%s",*p++);
printf("%s",++*p);
}
-----------------------------------------------------------------------------------------------
17. Output of the following program is
main()
{int i=0;
for(i=0;i<20;i++) c="-64;" i="-32" u ="-16;">i)
{printf("pass1,");
if(c<<2,x>>2);
}
-----------------------------------------------------------------------------------------------
18. What is the ouptut in the following program
main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(c<<2,x>>2);
}
-----------------------------------------------------------------------------------------------
25. Find the output for the following C program

#define swap1(a,b) a=a+b;b=a-b;a=a-b;
main()
{
int x=5,y=10;
swap1(x,y);
printf("%d %d\n",x,y);
swap2(x,y);
printf("%d %d\n",x,y);
}
int swap2(int a,int b)
{
int temp;
temp=a;
b=a;
a=temp;
return;
}
-----------------------------------------------------------------------------------------------
26. Find the output for the following C program
main()
{
char *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}
-----------------------------------------------------------------------------------------------
27. Find the output for the following C program
#include
main()
{
char *p1;
char *p2;
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,"Ramco");
strcpy(p2,"Systems");
strcat(p1,p2);
printf("%s",p1);
}
-----------------------------------------------------------------------------------------------
28. Find the output for the following C program
# define TRUE 0
some code
while(TRUE)
{
some code
}
-----------------------------------------------------------------------------------------------
29. struct list{
int x;
struct list *next;
}*head;

the struct head.x =100

Is the above assignment to pointer is correct or wrong ?
-----------------------------------------------------------------------------------------------
30.What is the output of the following ?
int i;
i=1;
i=i+2*i++;
printf(%d,i);
-----------------------------------------------------------------------------------------------
31. FILE *fp1,*fp2;
fp1=fopen("one","w")
fp2=fopen("one","w")
fputc('A',fp1)
fputc('B',fp2)
fclose(fp1)
fclose(fp2)
}
Find the Error, If Any?
-----------------------------------------------------------------------------------------------
32. #define MAN(x,y) (x)>(y)?(x):(y)
{int i=10;
j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}
-----------------------------------------------------------------------------------------------
33.void main()
{
int i=7;
printf("%d",i++*i++);
}
-----------------------------------------------------------------------------------------------
34.How will u terminate the statement?
-----------------------------------------------------------------------------------------------
35.select the wrong one
a.a+=1;
b.a*=2;
c.a**=1;
d.a>>=1;
-----------------------------------------------------------------------------------------------
36.pick the odd one
a.malloc
b.calloc
c.new
-----------------------------------------------------------------------------------------------
37.main()
{
char **p=="Hello";
printf("%s",**p);
}
-----------------------------------------------------------------------------------------------
38.main()
{
printf("%d%c\n");
printf("%d%c\n");
}
-----------------------------------------------------------------------------------------------
39.main()
{
int x==5;
printf("%d%d",x++,++x);
}
-----------------------------------------------------------------------------------------------
40.main()
{
int x==4;
printf("%d",printf(" %d %d ",x,x) );
}
-----------------------------------------------------------------------------------------------
41.main()
{
union
{
int i;
char p;
struct
{
int t;
char e;
char o;
};
};
printf("%d\n",sizeof(l) );
}
-----------------------------------------------------------------------------------------------
42.main()
{
int i==0,n==6;
while(n--0);
i+==n;
printf("%d\n",i);
}
-----------------------------------------------------------------------------------------------
43.a=3,b=2,c=1;
What's the value of k?
k= a< a="=" a=" 1;" i="=" i="=" a="e" s="'R';" i="=" a1="=" a2="=" t="¡;" a1="¢;" a2=" t;" s1="=" s2="s1;" temp=" s1;" a1= "new" a2= "dictionary" t="¡;" a1="¢;" a2="t;" s1=" s2;" s2=" s1;" temp=" s1;" p="=">add(dharma) && (*p)->harma)
"harma" (after printing, p->add(hewlett-packard) &&(*p)->harma)
"ewlett-packard"
-----------------------------------------------------------------------------------------------

17. (d)

18. (c)

19. (b)

20. (a)

21. (b)

22. An empty string

23. 57 94

24. 5 20 1

25. 10 5

26. Samco Systems

27. RamcoSystems

28. This won't go into the loop as TRUE is defined as 0

29. Wrong

30. 4

31. no error. But It will over writes on same file.

32. 10 5 0

33. 56

34. ;

35. C

36. C

37. Garbage or nothing

38. Garbage Value

39. 6 6

40. 4 4 5

41. 4

42. -1

43. 0

44. 3

45. 16 21

46. UPPER CASE

47. 5 4 3 2 1

48. (newdictionary)-(dictionarynew)

49. (newdictionary)-(dictionarynew)

50. 50

C++ Interview Questions: Part 9

31. When can you tell that a memory leak will occur?
Answer: A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory.

32.What is a parameterized type?
Answer: A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters.

33. Differentiate between a deep copy and a shallow copy?
Answer:
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Explanation:
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.

34. What is an opaque pointer?
Answer:
A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files.

35. What is a smart pointer?
Answer:
A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example:
template
class smart_pointer
{
public:
smart_pointer(); // makes a null pointer
smart_pointer(const X& x) // makes pointer to copy of x

X& operator *( );
const X& operator*( ) const;
X* operator->() const;

smart_pointer(const smart_pointer &);
const smart_pointer & operator =(const smart_pointer&);
~smart_pointer();
private:
//...
};
This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
smart_pointer p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p; p->raise_salary(0.5);

36. What is reflexive association?
Answer:
The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example:
Printer is-a printer.

37. What is slicing?
Answer:
Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.

Explanation:

Consider the following class declaration:
class base
{
...
base& operator =(const base&);
base (const base&);
}
void fun( )
{
base e=m;
e=m;
}
As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency.

38. What is name mangling?
Answer:
Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.

Example:
In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration:
class Bar
{
public:
int ival;
...
};
ival becomes something like:
// a possible member name mangling
ival__3Bar
Consider this derivation:
class Foo : public Bar
{
public:
int ival;
...
}
The internal representation of a Foo object is the concatenation of its base and derived class members.
// Pseudo C++ code
// Internal representation of Foo
class Foo
{
public:
int ival__3Bar;
int ival__3Foo;
...
};
Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).

39. What are proxy objects?
Answer:
Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object.

40. Differentiate between declaration and definition in C++.
Answer:
A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program.

A declaration is a definition unless:

 it declares a function without specifying its body,
 it contains an extern specifier and no initializer or function body,
 it is the declaration of a static class data member without a class definition,
 it is a class name definition,
 it is a typedef declaration.

A definition is a declaration unless:

 it defines a static class data member,
 it defines a non-inline member function.

41. What is cloning?
Answer:
An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.

42. Describe the main characteristics of static functions.
Answer:

The main characteristics of static functions include,

 It is without the a this pointer,
 It can't directly access the non-static members of its class
 It can't be declared const, volatile or virtual.
 It doesn't need to be invoked through an object of its class, although for convenience, it may.

43. Will the inline function be compiled as the inline function always? Justify.
Answer:
An inline function is a request and not a command. Hence it won't be compiled as an inline function always.

Explanation:

Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.

44. Define a way other than using the keyword inline to make a function inline.
Answer:
The function must be defined inside the class.

45. How can a '::' operator be used as unary operator?
Answer:
The scope operator can be used to refer to members of the global namespace. Because the global namespace doesn’t have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name.

46. What is placement new?
Answer:
When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it.
class Widget
{
public :
Widget(int widgetsize);
...
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

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