Friday, 27 January 2012

C++ Interview Questions


Introduction

You maybe a great programmer who uses C/C++ everyday but if you really wantthat new job, it maybe a good idea to review the core principles of C/C++before the interview. I have compiled a list of 10 questions that I feel youshould know the answers to if you are applying for any C++ position. At the endof the article, I have also added some links to sites to help you prepare foryour interview.
What is thedifference between C and C++ ? Would you prefer to use one over the other ?

C is based on structured programming whereas C++ supports the object-orientedprogramming paradigm.Due to the advantages inherent in object-oriented programssuch as modularity and reuse, C++ is preferred. However almost anything thatcan be built using C++ can also be built using C.
What are theaccess privileges in C++ ? What is the default access level ?

The access privileges in C++ are private, public and protected. The defaultaccess level assigned to members of a class is private. Private members of aclass are accessible only within the class and by friends of the class.Protected members are accessible by the class itself and it's sub-classes.Public members of a class can be accessed by anyone.
What is dataencapsulation ?
DataEncapsulation is also known as data hiding. The most important advantage ofencapsulation is that it lets the programmer create an object and then providean interface to the object that other objects can use to call the methodsprovided by the object. The programmer can change the internal workings of anobject but this transparent to other interfacing programs as long as theinterface remains unchanged.
What isinheritance ?
Inheritance isthe process of deriving classes from other classes. In such a case, thesub-class has an 'is-a' relationship with the super class. For e.g. vehicle canbe a super-class and car can be a sub-class derived from vehicle. In this casea car is a vehicle. The super class 'is not a' sub-class as the sub-class ismore specialized and may contain additional members as compared to the superclass. The greatest advantage of inheritance is that it promotes generic designand code reuse.
What is multipleinheritance ? What are it's advantages and disadvantages ?
MultipleInheritance is the process whereby a sub-class can be derived from more thanone super class. The advantage of multiple inheritance is that it allows a classto inherit the functionality of more than one base class thus allowing formodeling of complex relationships. The disadvantage of multiple inheritance isthat it can lead to a lot of confusion when two base classes implement a methodwith the same name.
What ispolymorphism?
Polymorphismrefers to the ability to have more than one method with the same signature inan inheritance hierarchy. The correct method is invoked at run-time based onthe context (object) on which the method is invoked. Polymorphism allows for ageneric use of method names while providing specialized implementations forthem.
What do thekeyword static and const signify ?

When a class member is declared to be of a static type, it means that themember is not an instance variable but a class variable. Such a member isaccessed using Classname.Membername (as opposed to Object.Membername). Const isa keyword used in C++ to specify that an object's value cannot be changed.
How is memoryallocated/deallocated in C ? How about C++ ?

Memory is allocated in C using malloc() and freed using free(). In C++ thenew() operator is used to allocate memory to an object and the delete()operator is used to free the memory taken up by an object.
What is UML ?

UML refers to Unified Modeling Language. It is a language used to model OOproblem spaces and solutions.
What is thedifference between a shallow copy and a deep copy ?
A shallow copysimply creates a new object and inserts in it references to the members of theoriginal object. A deep copy constructs a new object and then creates in itcopies of each of the members of the original object.
Here are somemore interesting references on C++ interview preparation: be sure to check themout before your next interview. Good Luck!

The C++ Interview
These 40 questions and answers will helpyou land the assignment
by Alex Bykov
How do you rankyour C++ skills on a scale of 1 to 10?
This is oftenthe first question you will hear on an interview for a C++ contract. You willbe tempted to rate yourself high, and you should. This is your chance toconvince the client that you are just what he is looking for--an assertive andknowledgeable professional who will be productive either working on a team oron your own. Naturally, though, you should be able to support the ranking yougave yourself by doing well on the interview. This article will help youprepare for your C++ interview.
I put together alist of 40 questions that I have had to answer during numerous technicalinterviews in the past few years. You, too, will have to answer at least someof them during an interview. Even if you use C++ on a daily basis, it pays togo through the questions. Most of us, no matter how experienced, use only asegment of the language that we are most comfortable with. Brief answers areincluded, but you can find more information in the referenceslisted.
Q1. Is thereanything you can do in C++ that you cannot do in C?
A1. No. There isnothing you can do in C++ that you cannot do in C. After all you can write aC++ compiler in C.
Q2. What isthe difference between C++ structure and C++ class?
A2. The defaultaccess level assigned to members of struct is public while the default accesslevel assigned to a class is private.
Q3. What isencapsulation?
A3. Encapsulationis welding of code and data together into objects.
Q4. What isinheritance?
A4. Inheritance isa mechanism through which a subclass inherits the properties and behavior ofits superclass.
Q5. What ispolymorphism?
A5. In Greek thismeans "many shapes." As a consequence of inheritance and virtualfunctions, a single task (for example, drawing a geometrical shape) can beimplemented using the same name (like draw()) and implemented differently (viavirtual functions) as each type in object hierarchy requires(circle.draw() orrectangle.draw()). Later, when a polymorphic object (whose type is not known atcompile time) executes the draw() virtual function, the correct implementationis chosen and executed at run time.
Q6. Whatwould you say if you saw "delete this" while reviewing your peer'scode?
A6. You shouldnever do this. Since compiler does not know whether the object was allocated onthe stack or on the heap, "delete this" could cause a disaster.
Q7. What isthe difference between public, protected, and private members of a class?
A7. Private membersare accessible only by members and friends of the class. Protected members areaccessible by members and friends of the class and by members and friends ofderived classes. Public members are accessible by everyone.
Q8. What isthe difference between non-virtual and virtual functions?
A8. The behavior ofa non-virtual function is known at compile time while the behavior of a virtualfunction is not known until the run time.
Q9. What is apure virtual function?
A9. "A purevirtual function is a function declared in a base class that has no definitionrelative to the base."
Q10. What isan abstract base class?
A10. It is a classthat has one or more pure virtual functions.
Q11. What isthe difference between MyClass p; and MyClass p();?
A11. MyClass p;creates an instance of class MyClass by calling a constructor for MyClass.MyClass p(); declares function p which takes no parameters and returns anobject of class MyClass by value.
Q12. How doyou know that your class needs a virtual destructor?
A12. If your classhas at least one virtual function, you should make a destructor for this classvirtual. This will allow you to delete a dynamic object through a pointer to abase class object. If the destructor is non-virtual, then wrong destructor willbe invoked during deletion of the dynamic object.
Q13. Why werethe templates introduced?
A13. Many datastructures and algorithms can be defined independently of the type of data theywork with. You can increase the amount of shared code by separatingdata-dependent portions from data-independent portions, and templates wereintroduced to help you do that.
Q14. What isa static member of a class?
A14. Static datamembers exist once for the entire class, as opposed to non-static data members,which exist individually in each instance of a class.
Q15. Whatfeature of C++ would you use if you wanted to design a member function thatguarantees to leave "thisÓ object unchanged?
A15. It is"const" as in: "int MyFunc (int test) const;"
Q16. Can youoverload a function based only on whether a parameter is a value or areference?
A16. No. Passing byvalue and by reference looks identical to the caller.
Q17. What isthe difference between function overloading and function overriding?
A17. Overloading isa method that allows defining multiple member functions with the same name butdifferent signatures. The compiler will pick the correct function based on the signature.Overriding is a method that allows the derived class to redefine the behaviorof member functions which the derived class inherits from a base class. Thesignatures of both base class member function and derived class member functionare the same; however, the implementation and, therefore, the behavior willdiffer.
Q18. Canderived class override some but not all of a set of overloaded virtual memberfunctions inherited from the base class?
A18. Compiler willallow this, but it is a bad practice since overridden member functions willhide all of the inherited overloads from the base class. You should reallyoverride all of them.
Q19. What isthe difference between assignment and initialization in C++?
A19. Assignmentchanges the value of the object that has already been constructed.Initialization constructs a new object and gives it a value at the same time.
Q20. When arecopy constructors called?
A20. Copyconstructors are called in three cases: when a function returns an object ofthat class by value, when the object of that class is passed by value as anargument to a function, and, finally, when you construct an object based onanother object of the same class (Circle c1=c2;).
Q21. Why doyou have to provide your own copy constructor and assignment operator forclasses with dynamically allocated memory?
A21. If you don't,the compiler will supply and execute the default constructor and the assignmentoperator, but they will not do the job correctly. The default assignmentoperator does memberwise assignment and the default copy constructor doesmemberwise copy. In both cases you will only assign and manipulate pointers todynamic memory, which will lead to memory leaks and other abnormalities. Youshould write your own assignment operator and copy constructor, which wouldcopy the pointer to memory so that each object has its own copy.
Q22. Doescompiler guarantee that initializers will be executed in the same order as theyappear on the initialization list?
A22. No. C++guarantees that base class subobjects and member objects will be destroyed inthe opposite order from which they were constructed. This means thatinitializers are executed in the order, which supports the above-mentionedguarantee.
Q23. What isfunction's signature?
A23. Function'ssignature is its name plus the number and types of the parameters it accepts.
Q24. Whatdoes extern "C" int func(int *, Foo) accomplish?
A24. It will turnoff "name mangling" for this function so that one can link to codecompiled by C compiler.
Q25. Why doC++ compilers need name mangling?
A25. Name manglingis the rule according to which C++ changes function's name into functionsignature before passing that function to a linker. This is how the linkerdifferentiates between different functions with the same name.
Q26. What isthe difference between a pointer and a reference?
A26. A referencemust always refer to some object and, therefore, must always be initialized;pointers do not have such restrictions. A pointer can be reassigned to point todifferent objects while a reference always refers to an object with which itwas initialized.
Q27. How canyou access the static member of a class?
A27.<ClassName>::<StaticMemberName>.
Q28. How areprefix and postfix versions of operator++() differentiated?
A28. The postfixversion of operator++() has a dummy parameter of type int. The prefix versiondoes not have dummy parameter.
Q29. Whatfunctions does C++ silently write and call?
A29. Constructors,destructors, copy constructors, assignment operators, and address-of operators.
Q30. What isthe difference between new/delete and malloc/free?
A30. Malloc/free donot know about constructors and destructors. New and delete create and destroyobjects, while malloc and free allocate and deallocate memory.
Q31. What isthe difference between delete and delete[ ]?
A31. Delete deletesone object; delete[ ] deletes an array of objects.
Q32. Name twocases where you MUST use initialization list as opposed to assignment inconstructors.
A32. Both non-staticconst data members and reference data members cannot be assigned values;instead, you should use initialization list to initialize them.
Q33. What isthe difference between const char *myPointer and char *const myPointer?
A33. Const char*myPointer is a non constant pointer to constant data; while char *constmyPointer is a constant pointer to non constant data.
Q34. Supposethat objects A, B, and C are instances of class MyClass (MyClass A, B, C;). Howshould you design an assignment operator so that the "A=B=C;"statement would be allowed by a compiler but "(A=B)=C;" would not beallowed by a compiler?
A34. Makeoperator=return a reference to a const object.
Q35. Is thereany problem with the following: char *a=NULL; char& p = *a;?
A35. The result isundefined. You should never do this. A reference must always refer to someobject.
Q36. Class Bis derived from class A. Function f is A's friend. Is f B's friend as well?
A36. No. Friendshipcannot be inherited.
Q37. Whatissue do auto_ptr objects address?
A37. If you useauto_ptr objects you would not have to be concerned with heap objects not beingdeleted even if the exception is thrown.
Q38. Whathappens when a function throws an exception that was not specified by anexception specification for this function?
A38. Unexpected() iscalled, which, by default, will eventually trigger abort().
Q39. Whyshould you prefer throw/catch mechanism to setjmp/longjmp?
A39. The mainproblem with longjmp() is that it does not destroy local objects properly.
Q40. Can youthink of a situation where your program would crash without reaching thebreakpoint which you set at the beginning of main()?
A40. C++ allows fordynamic initialization of global variables before main() is invoked. It ispossible that initialization of global will invoke some function. If thisfunction crashes the crash will occur before main() is entered.
If you feelcomfortable answering these questions, then rest assured that your chances ofimpressing any interviewer are very high. Be prepared to know basic computerscience concepts such as data structures, search and sort algorithms, basicdatabase concepts, etc. The client's needs will determine what particular branchof computer science you have to be familiar with, but you should always beready to implement the stock, the queue, and the linked list data structureswith either C or C++ programming languages. And know how to write your ownversion of strcpy (string copy) in C programming language since very often theyask you to do that.

MicrosoftInterview Questions & Answers

I recentlyvisited Microsoft's Silicon Valleycampus and interviewed with the Hotmailgroup. If you've never had a Microsoft interview, realize that they are verydifferent than the standard interview. You won't be asked any of thosequestions like, "What is your greatest weakness," or, "Where doyou want to be in five years?" Rather, a Microsoft interview typically containsa number of brain teasers and coding questions. In fact, you can read interview questions from my internshipinterviews.
Here are thequestions I was asked, accompanied with the answers right below the question!So, once you reach the end of the question, don't read any further unless youwant to immediately know the answer! Anyway, here goes:
Question: How could youdetermine if a linked list contains a cycle in it, and, at what node the cyclestarts?
Answer: There are anumber of approaches. The approach I shared is in time N (where N is the numberof nodes in your linked list). Assume that the node definition contains aboolean flag, bVisited.
struct Node {   ...   bool bVisited; };
Then, todetermine whether a node has a loop, you could first set this flag to false for all of thenodes:
// Detect cycle // Note: pHead points to the head of the list (assume already exists) Node *pCurrent = pHead; while (pCurrent) {   pCurrent->bVisited = false;   pCurrent = pCurrent->pNext; }
Then, todetermine whether or not a cycle existed, loop through each node. Aftervisiting a node, set bVisited to true. When you firstvisit a node, check to see if the node has already been visited (i.e., test bVisited == true). If it has,you've hit the start of the cycle!
bool bCycle = false; pCurrent = pHead; while (pCurrent && !pCycle) {   if (pCurrent->bVisited == true)     // cycle!     pCycle = true;   else   {     pCurrent->bVisited = true;     pCurrent = pCurrent->pNext;   } } 
A much betterapproach was submitted by 4Guys visitor George R., a Microsoftinterviewer/employee. He recommended using the following technique, which is intime O(N) and space O(1).
Usetwo pointers.
// error checking and checking for NULL at end of list omitted p1 = p2 = head;  do {  p1 = p1->next;  p2 = p2->next->next; } while (p1 != p2);
p2 is movingthrough the list twice as fast as p1. If the list is circular, (i.e. a cycle exists) itwill eventually get around to that sluggard, p1.
Thanks George!

Question: How would youreverse a doubly-linked list?
Answer: This problemisn't too hard. You just need to start at the head of the list, and iterate tothe end. At each node, swap the values of pNext and pPrev. Finally, set pHead to the lastnode in the list.
Node * pCurrent = pHead, *pTemp; while (pCurrent) {   pTemp = pCurrent->pNext;   pCurrent->pNext = pCurrent->pPrev;   pCurrent->pPrev = temp;      pHead = pCurrent;    pCurrent = temp; }

Question: Assume you havean array that contains a number of strings (perhaps char * a[100]). Each stringis a word from the dictionary. Your task, described in high-level terms, is todevise a way to determine and display all of the anagrams within the array (twowords are anagrams if they contain the same characters; for example, tales and slate are anagrams.)
Answer: Begin bysorting each element in the array in alphabetical order. So, if one element ofyour array was slate, it would berearranged to form aelst (use somemechanism to know that the particular instance of aelst maps to slate). At thispoint, you slate and tales would beidentical: aelst.
Next, sort theentire array of these modified dictionary words. Now, all of the anagrams aregrouped together. Finally, step through the array and display duplicate terms,mapping the sorted letters (aelst)back to the word (slate or tales).

Question: Given thefollowing prototype:
int compact(int * p, int size);
write a functionthat will take a sorted array, possibly with duplicates, and compact the array,returning the new length of the array. That is, if p points to anarray containing: 1,3, 7, 7, 8, 9, 9, 9, 10,when the function returns, the contents of p should be: 1, 3, 7, 8, 9, 10, with a length of 5 returned.
Answer: A single loopwill accomplish this.
int compact(int * p, int size) {   int current, insert = 1;   for (current=1; current < size; current++)     if (p[current] != p[insert-1])     {       p[insert] = p[current];       current++;       insert++;     } else       current++; }



Passing the C++Test
Securing success in an interview
Dr. Dobb'sJournalSpring 1998
By Al Stevens
Al, acontributing editor for Dr. Dobb's Journal, can be contacted atastevens@ddj.com.

In my August1996 Dr. Dobb's Journal "C Programming" column, I reportedthat someone with two to five years experience programming C++ can, accordingto a report in ComputerWorld, command $70,000 on either coast and$65,000 in the central part of the country. The opportunities seem even betterfor programmers with Win32 programming experience, particularly Windows NT C++and Microsoft Foundation Classes (MFC) programming experience.
http://ads.ddj.com/redirect/132/973585052


http://ads.ddj.com/redirect/132/973585052
Of course, noone expects the typical college graduate to have two or more years of solidexperience programming a particular platform. The range of your experiencedepends on how your time was distributed between the usual class workload, labtime, research projects, and any part-time jobs you might have had.Nonetheless, there is a demand for qualified people and a shortage of qualifiedpeople. Employers will be looking to entry-level recent graduates to take upthe slack. That's where you come in. You'll be competing with all those othergrads for those jobs, and, if the ComputerWorld report is a forecast ofwhat's coming, in two years, this summer's entry-level programmers will be theveterans knocking down those respectable salaries. The trick is to get your footin the door now. Let's see if we can help prepare you to impress the folks whoare interviewing new programmers.
Windows NTprogramming is Win32 programming, which, unless you are writing deepsystems-level code, is the same thing as Windows 95 programming. If you don'thave an NT system handy, latch onto a Windows 95 PC and a copy of Visual C++4.0 or later. I don't want you to neglect your studies these last few months --you have to get through finals before anyone talks to you about a job -- but thereare a few things you can do to prepare to demonstrate an understanding of theprogramming environments that employers want to discuss. That demonstrationcould be just the advantage that edges out the competition.
You need to showin a brief interview that you understand and can work with C++ in the Win32development environment. Those are two different curves, both of which aresteep. Let's start with C++.
I put together alist of questions that employers can ask potential programming employees toqualify them as to the extent of their C++ knowledge. These, I think, arerepresentative of the kinds of things that you will be asked. I published thequestions and my opinions about appropriate answers in my column. From theresponse I got from readers, I learned that many practicing C++ programmerscannot answer some of these questions. The pop quiz, as one reader labeled it,sent many programmers back to their reference books. They had fallen into arut, using a comfortable subset of the language, and, as a consequence, werenot using C++ to its full potential. Other readers suggested more questions anda broader approach to qualifying an applicant. Those suggestions caused me toevaluate my approach and adjust it.
I dividedapplicants into three groups: those who understand C++ well enough to use it asan improved C; those who have experience designing C++ classes; and those whoare so motivated that they keep up with the recently approved specification ofstandard C++.
I will statehere that anyone who has read and understands my book, Teach Yourself C++(MIS Press, about to be released in its 5th edition), or who has completed thetutorials on The Al Stevens Cram Course on C/C++ CD-ROM (available from Dr.Dobb's Journal), can ace all three parts of this quiz. If you consider thatstatement to be a shameless plug, then you fully understand my motives. It'strue, nonetheless. Let's get on with it.
A lot of whatfollows was taken directly from my August and September 1996 "CProgramming" columns in Dr. Dobb's Journal. I reworded some of itto reflect your concerns and to incorporate some changes and corrections thatother readers sent to me.
Questions for All C++ Applicants
Here's the firstgroup of C++ questions and my opinions about what some acceptable answers wouldbe. These questions do not cover C++ wall-to-wall, of course. I selected themas being typical of the kinds of things that all C++ programmers should beexpected to know. There are five questions. Three correct answers is a goodscore.
Q: How do you linka C++ program to C functions?
A: By using the extern"C" linkage specification around the C function declarations.
You should knowabout mangled function names and type-safe linkages. Then you should explainhow the extern "C" linkage specification statement turns thatfeature off during compilation so that the linker properly links function callsto C functions. Another acceptable answer is "I don't know. We never hadto do that." Merely describing what a linker does would indicate to me thatyou do not understand the issue that underlies the question.
Q: Explain thescope resolution operator.
A: The scoperesolution operator permits a program to reference an identifier in the globalscope that has been hidden by another identifier with the same name in thelocal scope.
The answer canget complicated. It should start with "colon-colon," however. (Somereaders had not heard the term, "scope resolution operator," but theyknew what :: means. You should know the formal names of such things so that youcan understand all communication about them.) If you claim to be well into thedesign or use of classes that employ inheritance, you tend to addressoverriding virtual function overrides to explicitly call a function higher inthe hierarchy. That's good knowledge to demonstrate, but address your commentsspecifically to global scope resolution. Describe C++'s ability to override theparticular C behavior where identifiers in the global scope are always hiddenby similar identifiers in a local scope.
Q: What are thedifferences between a C++ struct and C++ class?
A: The defaultmember and base class access specifiers are different.
This is one ofthe commonly misunderstood aspects of C++. Believe it or not, many programmersthink that a C++ struct is just like a C struct, while a C++ classhas inheritance, access specifiers, member functions, overloaded operators,and so on. Some of them have even written books about C++. Actually, the C++ structhas all the features of the class. The only differences are that a structdefaults to public member access and public base class inheritance, and a classdefaults to the private access specifier and private base classinheritance. Getting this question wrong does not necessarily disqualify youbecause you will be in plenty of good company. Getting it right is a definiteplus.
Q: How many waysare there to initialize an int with a constant?
A: Two.
There are twoformats for initializers in C++ as shown in Example1. Example 1(a) uses thetraditional C notation, while Example 1(b)uses constructor notation. Many programmers do not know about the notation in Example 1(b), although they should certainly knowabout the first one. Many old-timer C programmers who made the switch to C++never use the second idiom, although some wise heads of C++ profess to preferit.
A reader wroteto tell me of two other ways, as shown in Examples2(a) and 2(b), which made me think that maybe the answer could beextended even further to include the initialization of an int functionparameter with a constant argument from the caller.
Q: How doesthrowing and catching exceptions differ from using setjmp and longjmp?
A: The throwoperation calls the destructors for automatic objects instantiated since entryto the try block.
Exceptions arein the mainstream of C++ now, so most programmers, if they are familiar with setjmpand longjmp, should know the difference. Both idioms return a programfrom the nested depths of multiple function calls to a defined position higherin the program. The program stack is "unwound" so that the state ofthe program with respect to function calls and pushed arguments is restored asif the calls had not been made. C++ exception handling adds to that behaviorthe orderly calls to the destructors of automatic objects that wereinstantiated as the program proceeded from within the try block toward wherethe throw expression is evaluated.
It's okay todiscuss the notational differences between the two idioms. Explain the syntaxof try blocks, catch exception handlers, and throw expressions. Thenspecifically address what happens in a throw that does not happen in a longjmp.Your answer should reflect an understanding of the behavior described in theanswer just given.
One valid reasonfor not knowing about exception handling is that your experience is exclusivelywith older C++ compilers that do not implement exception handling. I wouldprefer that you have at least heard of exception handling, though.
It is notunusual for C and C++ programmers to be unfamiliar with setjmp/ longjmp.Those constructs are not particularly intuitive. A C programmer who has writtenrecursive descent parsing algorithms will certainly be familiar with setjmp/longjmp. Others might not, and that's acceptable. In that case, you won'tbe able to discuss how setjmp/longjmp differs from C++ exceptionhandling, but let the interview turn into a discussion of C++ exceptionhandling in general. That conversation will reveal to the interviewer a lotabout your overall understanding of C++.
Questions for Class Designers
The next groupof questions explores your knowledge of class design. There are eightquestions. Five out of eight is a good score.
Q: What is yourreaction to this line of code?
    deletethis;
A: It's not a goodpractice.
A goodprogrammer will insist that the statement is never to be used if the class isto be used by other programmers and instantiated as static, extern, orautomatic objects. That much should be obvious.
The code has twobuilt-in pitfalls. First, if it executes in a member function for an extern,static, or automatic object, the program will probably crash as soon as thedelete statement executes. There is no portable way for an object to tell thatit was instantiated on the heap, so the class cannot assert that its object isproperly instantiated. Second, when an object commits suicide this way, theusing program might not know about its demise. As far as the instantiatingprogram is concerned, the object remains in scope and continues to exist eventhough the object did itself in. Subsequent dereferencing of the pointer canand usually does lead to disaster.
A reader pointedout that a class can ensure that its objects are instantiated on the heap bymaking its destructor private. This idiom necessitates a kludgy DeleteMekind of function because the instantiator cannot call the delete operator forobjects of the class. The DeleteMe function would then use "deletethis."
I got a lot ofmail about this issue. Many programmers believe that delete this is avalid construct. In my experience, classes that use delete this whenobjects are instantiated by users usually spawn bugs related to the idiom, mostoften when a program dereferences a pointer to an object that has alreadydeleted itself.
Q: What is adefault constructor?
A: A constructorthat has no arguments or one where all the arguments have default argumentvalues.
If you don'tcode a default constructor, the compiler provides one if there are no otherconstructors. If you are going to instantiate an array of objects of the class,the class must have a default constructor.
Q: What is aconversion constructor?
A: A constructorthat accepts one argument of a different type.
The compileruses this idiom as one way to infer conversion rules for a class. A constructorwith more than one argument and with default argument values can be interpretedby the compiler as a conversion constructor when the compiler is looking for anobject of the type and sees an object of the type of the constructor's firstargument.
Q: What is thedifference between a copy constructor and an overloaded assignment operator?
A: A copyconstructor constructs a new object by using the content of the argumentobject. An overloaded assignment operator assigns the contents of an existingobject to another existing object of the same class.
First, you mustknow that a copy constructor is one that has only one argument, which is areference to the same type as the constructor. The compiler invokes a copyconstructor wherever it needs to make a copy of the object, for example to passan argument by value. If you do not provide a copy constructor, the compilercreates a member-by-member copy constructor for you.
You can writeoverloaded assignment operators that take arguments of other classes, but thatbehavior is usually implemented with implicit conversion constructors. If youdo not provide an overloaded assignment operator for the class, the compilercreates a default member-by-member assignment operator.
This discussionis a good place to get into why classes need copy constructors and overloadedassignment operators. By discussing the requirements with respect to datamember pointers that point to dynamically allocated resources, you demonstratea good grasp of the problem.
Q: When should youuse multiple inheritance?
A: There arethree acceptable answers: "Never," "Rarely," and "Whenthe problem domain cannot be accurately modeled any other way."
There are somefamous C++ pundits and luminaries who disagree with that third answer, so becareful.
Let's digress toconsider this issue lest your interview turn into a religious debate. Consideran Asset class, Building class, Vehicle class, and CompanyCarclass. All company cars are vehicles. Some company cars are assets because theorganizations own them. Others might be leased. Not all assets are vehicles.Money accounts are assets. Real-estate holdings are assets. Some real-estateholdings are buildings. Not all buildings are assets. Ad infinitum. When youdiagram these relationships, it becomes apparent that multiple inheritance isan intuitive way to model this common problem domain. You should understand,however, that multiple inheritance, like a chainsaw, is a useful tool that hasits perils, needs respect, and is best avoided except when nothing else willdo. Stress this understanding because your interviewer might share the commonbias against multiple inheritance that many object-oriented designers hold.
Q: What is avirtual destructor?
A: The simpleanswer is that a virtual destructor is one that is declared with the virtualattribute.
The behavior ofa virtual destructor is what is important. If you destroy an object through apointer or reference to a base class, and the base-class destructor is notvirtual, the derived-class destructors are not executed, and the destructionmight not be complete.
Q: Explain the ISAand HASA class relationships. How would you implement each in a class design?
A: A specializedclass "is a" specialization of another class and, therefore, has theISA relationship with the other class. An Employee ISA Person.This relationship is best implemented with inheritance. Employee is derivedfrom Person. A class may have an instance of another class. For example,an Employee "has a" Salary, therefore the Employeeclass has the HASA relationship with the Salary class. This relationshipis best implemented by embedding an object of the Salary class in the Employeeclass.
The answer tothis question reveals whether you have an understanding of the fundamentals ofobject-oriented design, which is important to reliable class design.
There are otherrelationships. The USESA relationship is when one class uses the services ofanother. The Employee class uses an object (cout) of the ostreamclass to display the employee's name onscreen, for example. But if you get ISAand HASA right, you usually don't need to go any further.
Q: When is atemplate a better solution than a base class?
A: When you aredesigning a generic class to contain or otherwise manage objects of othertypes, when the format and behavior of those other types are unimportant totheir containment or management, and particularly when those other types areunknown (thus the genericity) to the designer of the container or manager class.
Prior totemplates, you had to use inheritance; your design might include a generic Listcontainer class and an application-specific Employee class. To putemployees in a list, a ListedEmployee class is multiply derived(contrived) from the Employee and List classes. These solutionswere unwieldy and error-prone. Templates solved that problem.
Questions for ANSI-KnowledgeableApplicants
There are sixquestions for those who profess knowledge of the progress of the ANSIcommittee. If you claim to have that much interest in the language, you shouldknow the answers to all these questions.
Q: What is amutable member?
A: One that can bemodified by the class even when the object of the class or the member functiondoing the modification is const.
Understandingthis requirement implies an understanding of C++ const, which manyprogrammers do not have. I have seen large class designs that do not employ theconst qualifier anywhere. Some of those designs are my own early C++efforts. One author suggests that some programmers find const to be sucha bother that it is easier to ignore const than to try to use itmeaningfully. No wonder many programmers don't understand the power andimplications of const. Someone who claims to have enough interest in thelanguage and its evolution to keep pace with the ANSI deliberations should notbe ignorant of const, however.
Q: What is anexplicit constructor?
A: A conversionconstructor declared with the explicit keyword. The compiler does notuse an explicit constructor to implement an implied conversion of types. Itspurpose is reserved explicitly for construction.
Q: What is theStandard Template Library?
A: A library ofcontainer templates approved by the ANSI committee for inclusion in thestandard C++ specification.
An applicant whothen launches into a discussion of the generic programming model, iterators,allocators, algorithms, and such, has a higher than average understanding ofthe new technology that STL brings to C++ programming.
Q: Describerun-time type identification.
A: The ability todetermine at run time the type of an object by using the typeid operatoror the dynamic_cast operator.
Q: What problemdoes the namespace feature solve?
A: Multipleproviders of libraries might use common global identifiers causing a namecollision when an application tries to link with two or more such libraries.The name-space feature surrounds a library's external declarations with aunique namespace that eliminates the potential for those collisions.
This solutionassumes that two library vendors don't use the same namespace, of course.
Q: Are there anynew intrinsic (built-in) data types?
A: Yes. The ANSIcommittee added the bool intrinsic type and its true and false valuekeywords and the wchar_t data type to support character sets wider thaneight bits.
Other apparentnew types (string, complex, and so forth) are implemented asclasses in the Standard C++ Library rather than as intrinsic types.
In my originalcolumn, I left out wchar_t even though I should have known about it.Several readers wrote to correct me. I tell you this now to emphasize that evenI would not have scored 100 percent on my own test.
Understanding Win32
I haven't puttogether a list of questions that you should know about the Win32 API becausethe subject is way too broad to cover that way. There's no way that I couldguess what an interviewer is likely to ask. Instead, I'm going to tell you howto become expert enough to get through an interview. You'll have to cram thiswork into your otherwise busy student's schedule. I don't know how to tell youwhere to find the time, but if you can do it, it's worth it. Forsake the sociallife for the next several months. Try to get by without sleeping. (It's easy.You do all the things you would otherwise do, but you do them tired.) You areinvesting in your future, and this might be the most profitable time you'llever spend. Don't, of course, neglect your other studies.
You'll need aWindows 95 (or NT) system with Visual C++. Run the tutorials that the VC++online books include. Get comfortable with the programming environment -- theeditor, the debugger, the online documentation, the class wizard, the resourceeditor, and so on.
Next, you needtwo good books about Windows and MFC programming. These books are the classic ProgrammingWindows 95, by Charles Petzold, and Programming Windows 95 with MFC,by Jeff Prosise (both published by Microsoft Press). Read the Petzold bookcover to cover. Do it at your computer and run the programs that Charlesincludes. Step through them with the VC++ debugger. Get a solid foundation inthe Win32 API, the Windows event-driven, message-based programming model, andthe Windows way of using resources -- menus, dialog boxes, controls, and so on.
Now, readProsise. Learn the MFC application/document/view architecture. Learn how theMFC class library encapsulates those things and the Windows resources. Run allof Jeff's programs with the debugger just as you did Charles's. Be aware thatthe debugger steps into all the MFC code. If you find yourself in the depths ofan MFC constructor, for example, use the "Step out of" command to getback to the example. Eventually you'll learn to anticipate that and step overstatements that would lead you into the vapor.
Here's the bestadvice I can give you. With both these books, when you are running the exampleprograms through the debugger, never step out of a line of code until you fullyunderstand what the line of code is doing and why. If the book is unclear aboutit, and if, after wracking your brain and exhausting all your resources, youcan't figure it out, send me a message at astevens@ddj.com. If I can't figureit out, I'll find someone who can.
This offer isgood until December 24, 1999. If you don't have a job by then, you can havemine, because that's when I plan to get out of this business to avoid the Year2000 fiasco.
How to Comport Yourself in the Interview
Bear with me nowwhile I patronize you for a moment. I've sat through enough interviews to knowwhat rings the chimes of an interviewer and what turns them cold. This is goingto be like one of those motivational speeches that people buy on cassettes fromlate night TV pitchmen. Inasmuch as you already paid for the magazine, considerthis one to be free.
Remember, no oneexpects you to demonstrate the breadth of experience and judgement that comeswith years of experience. You should not be expected to know the relativemerits of every compiler, operating system, application framework, and so on.You should know what those things are, and, being a smart young person, you areexpected to have and voice strong opinions based on your limited experience,but those opinions need not demonstrate anything more than the youthfulexuberance and enthusiasm to which you are naturally entitled. You are bullet-proof,beer is food, and all's right with the world.
Relax in theinterview and be yourself. It is not an adversarial situation. The companyreally wants you to be the one. Most of us hate interviewing and hope abovehope that the right person shows up in the first session so we can get out ofhaving to do any more interviews.
Above all, don'tpretend to know more than you do. Be truthful when you do not know an answer.Don't try to guess what the interviewer wants to hear. Don't be afraid to ask,"What are you getting at?" Tell the interviewer that, given thechance, you can learn whatever you lack in plenty of time to be of usefulservice to the company. Most programming is intuitive to someone like yourselfwho has the aptitude. Make them know that you understand that concept and canapply it. The successful applicant is assured and confident. Make theinterviewer feel that by hiring you, the company will solve its programmingproblems.
Here's what elsenot to do. I know I just told you to be yourself, but, please, avoid makingsocial and political statements with your appearance. You have no way ofknowing what the interviewer's biases and prejudices are, and that's the personwhose muster you must pass today, even if on the job you'd never see that personagain. Sometimes the initial screening is done by personnel types who wouldn'tknow a byte if it bit them. Dress and groom yourself neatly and neutrally. Tryto look capable and professional. You can retreat to your own style, slob orfop, after you get the job and prove your worth.
Express awillingness to relocate anywhere and work long hours on any kind ofapplication. Insist, however, that you want to design programs and write code.You are not a typist, shipping clerk, computer operator, data-entry person,manual writer, coffee maker, driver, gopher, or tech-support phone person.Those are fine professions, but not for you. You are a programmer. That's whatyou do best and that's what they need most. Emphasize that you want to workwith the best technical people that the company has so that you can learn.Interviewers like to hear that.
Finally, don'tget discouraged. You won't get an offer for every interview, and you'll getsome offers that are unacceptable. Keep your spirits up, apply for every job thatlooks appealing, and spend your evenings sharpening your programming skills athome. If you see a job that you want, don't be dissuaded by an imposing list ofqualifications that you do not possess. Chances are, the company won't findanyone with all the right skills anyway. Go for it and convince theinterviewers that you can learn what you need to know.
Do these thingsand the right job will find you.

C++ Questions
·        Whatare the major differences between C and C++?
·        Whatare the differences between newand malloc?
·        Whatis the difference between deleteand delete[]?
·        Whatare the differences between a struct in C and in C++?
·        Whatare the advantages/disadvantages of using #define?
·        Whatare the advantages/disadvantages of using inline and const?
·        Whatis the difference between a pointer and a reference?
·        Whenwould you use a pointer? A reference?
·        Whatdoes it mean to take the address of a reference?
·        Whatdoes it mean to declare a function or variable as static?
·        Whatis the order of initalization for data?
·        Whatis name mangling/name decoration?
·        Whatkind of problems does name mangling cause?
·        Howdo you work around them?
·        Whatis a class?
·        Whatare the differences between a struct and a class in C++?
·        Whatis the difference between public, private, and protected access?
·        Forclass CFoo { }; what defaultmethods will the compiler generate for you>?
·        Howcan you force the compiler to not generate them?
·        Whatis the purpose of a constructor? Destructor?
·        Whatis a constructor initializer list?
·        Whenmust you use a constructor initializer list?
·        Whatis a:
·        Constructor?
·        Destructor?
·        Defaultconstructor?
·        Copyconstructor?
·        Conversionconstructor?
·        Whatdoes it mean to declare a...
·        memberfunction asvirtual?
·        memberfunction asstatic?
·        memberfunction asstatic?
·        membervarible as static?
·        destructoras static?
·        Canyou explain the term "resource acqusition is initialization?"
·        Whatis a "pure virtual" member function?
·        Whatis the difference between public, private, and protected inheritance?
·        Whatis virtual inheritance?
·        Whatis placement new?
·        Whatis the difference between operator new and the new operator?
·        Whatis exception handling?
·        Explainwhat happens when an exception is thrown in C++.
·        Whathappens if an exception is not caught?
·        Whathappens if an exception is throws from an object's constructor?
·        Whathappens if an exception is throws from an object's destructor?
·        Whatare the costs and benefits of using exceptions?
·        Whenwould you choose to return an error code rather than throw an exception?
·        Whatis a template?
·        Whatis partial specialization or template specialization?
·        Howcan you force instantiation of a template?
·        Whatis an iterator?
·        Whatis an algorithm (in terms of the STL/C++ standard library)?
·        Whatis std::auto_ptr?
·        Whatis wrong with this statement? std::auto_ptr ptr(new char[10]);
·        Itis possible to build a C++ compiler on top of a C compiler. How would you dothis? (Note: I've only asked this question once; and yes, he understood that Iwas asking him how cfront was put together. We hired him.)/i>
Code Snippets
I like to putthese up on a whiteboard, and ask questiosn about them.

What output doesthe following code generate? Why?
What output does it generate if you make A::Foo() a pure virtual function?
             classA {
                   A(){ this->Foo(); }
                   virtualvoid Foo() { cout << "A::Foo()" << endl; }
             };

             classB : public A {
                   B(){ this->Foo(); }
                   virtualvoid Foo() { cout << "A::Foo()" << endl; }
             };

             intmain(int, char**)
             {
                   A     objectA;
                   B     objectB;

                   return0;
             }
     

What output doesthis program generate as shown? Why?
             classA {
                   A(){ cout << "A::A()" << endl; }
                   ~A(){ cout << "A::~A()" << endl; throw"A::exception"; }
             };

             classB {
                   B(){ cout << "B::B()" << endl; throw"B::exception"; }
                   ~B(){ cout << "B::~B()"; }
             };

             intmain(int, char**)
             {
                   try
                   {
                          cout<< "Entering try...catch block" << endl;

                          A     objectA;
                          B     objectB;

                          cout<< "Exiting try...catch block" << endl;
                   }
                   catch(char* ex)
                   {
                          cout<< ex << endl;
                   }

                   return0;
             }
     

Misc. Questions
·        What'sthe difference between SQL, DDL, and DML?
·        What'sa join? An inner join? An outer join?
·        DescribeHTTP.
·        What'sa design pattern?
·        Canyou explain the singleton, vistor, facade, or handle class design pattern?


C++Test / Typical Interview Questions
Check out thefollowing links for interview help.
http://www.collegegrad.com/intv/intrview.html
Level 2
What is theoutput of the following code segment and why?
#include<stdio.h>
void main ( void )
{
unsigned number = 100;
if (number > (unsigned) -1 )
printf("Hello");
else
printf("There");
}

Output : There
Reason : When -1 isconverted to unsigned it is converted to the largerst
unsigned number, 4294967295 in Visual C++ version 5.0.

Level 1

Describe the output from the following code segment.

#include <stdio.h>
void main ( void)
{
for ( int i=0;i<100; ++i);
{
printf("%d",i);
}
}

Output : 100

Reason : The for loop has a ";" at the end of it, so the blockof code
that follows is executed after the for loop is run 100 times.

Level 1

What is the output of the following code segment?
#include<stdio.h>

void main ( void )
{
int value1, value2;
int * retValue;

value1 = -1;
value2 = value1 + 4;

*retValue = value1 * value2;
printf("%d", retValue);
}


Output : Could be anything

Reason : We are printing the address of retValue not the value ofretVale.

Level 3
What is theoutput of the following code?
#include<iostream.h>

class TValue {
protected:
int value;
public:
TValue (int n) { value = n; }
int GetValue (void) { return value; }
virtual int GetData (void) { return value; }
};

class TMult: public TValue {
protected:
int multiplier;
public:
TMult (int n, int m): TValue (n) {multiplier = m;}
int GetValue(void) { return value * multiplier;}
virtual int GetData(void) { return value * multiplier;}
};

void main(void)
{

TValue tVal(10);
TMult tMul(10, 2);
TValue *pVal, *pVal2;

pVal = new TMult(10,2);
pVal2 = new TMult(10,2);

cout << "tVal : " << tVal.GetValue() << endl;
cout << "tMult: " << tMul.GetValue() << endl;
cout << "pVal GetValue() : " << pVal->GetValue()<< endl;

cout << "pVal2 GetData(): " << pVal->GetData()<< endl;

}
Output:
tVal : 10
tMult: 20
pVal GetValue() : 10
pVal2 GetData(): 20

Reason: See the definition of virtual member below.
What is theresult of the following bit shifting segment of code?

What is serialization?

Answer: Serialization is the process of storing the state of an object for thepurpose of loading it at another time. When an object is serialized,information about the type of object is written to the storage along withinformation and data about the object. When an object is deserialized, the sameprocess happens in reverse, and the object is loaded and created from the inputstream.
What is a class?

A class allows data and functions to be bundled together and used as if theyare a single element. Classes typically model real-world concepts that haveboth data and some sort of behavior.
What is aninstance of a class?
Answer: Aninstance of a class, sometimes called an object, is an occurrence of a class.An instance of one of your classes can be used or manipulated inside yourprograms.
Classes andinstances of classes are not the same things -- think of a class as thedescription of an object; an instance of a class is a concrete occurrence ofthat class.
What is thedifference between TCP/IP and UDP/IP?
TCP (TransportControl Protocol ) and UDP ( user datagram protocal) are both methods oftransport protocols. IP stands for internet protocal. TCP/IP is like atelephone connection for communication to take place there must be a sender andreceiver; there must be a connection made. UDP/IP does not require a connectionto be made, similar to the mail system. You can post a letter without someonenecessarily receiving it.
TCP/IP isdesigned to solve modern computer communication problems by allowing differentcomputers to communicate across multiple networks.
IP or the"Internet Protocol" will provide the thread that allows data to findits way between two computers across multiple networks.
TCP or the"Transport Control Protocol" will provide the "reliabletransport" or assurance that data is sent and received between the twocomputers and their respective application programs.
Whatis the difference between a class and a structure?
In a class,members are private by default. In a structure, members are public by default
Which of thefollowing operators are control structures: >= , <, &&, |, &,<=, || ?
&& and|| are short-circuit logical operators. ie. flag1 && flag2 evaluates to
if (flag1) { if(flag2) { ... } }
What was the ++operator designed for originally?
What is a binarytree?
A binary tree isan ordered tree in which each internal node has either zero or two children.Some definitions allow for simply
What is a binarysearch tree?
Each internalnode v stores an element e such that the elements stored in the left subtree ofv are less than or equal to e, and the elements stored in the right subtree ofv are greater than or equal to e.
Name two stringcompression algorithms.
Huffman Codingand
Name two patternmatching algorithms.
Knuth-Morris-PrattAlgorithm and Boyer-Moore Algorithm
AllObject Oriented Languages share three common defining traits explain these
Encapsulation,Polymorphism, and Inheritence.
Inheritanceis the process by which one object can acquire the properties
of another, be more specific?
An object caninherit a general set of properties to which it can add those features that arespecific only to itself. Inheritance is important because it allows an objectto support the concept of hierarchical classification.
What is aVirtual Member Function?
Calls to virtualmember functions are linked at runtime (by a technique known as late binding).Calls to regular member functions are linked at compile time (early binding).Virtual member functions and late binding make it possible for objects todetermine their own behavior at runtime - the chief characteristic ofpolymorphism.
How many gasstations are there in Canada?
What are youstrengths?
What are youweaknesses or areas for improvement?
What is the mostcomplicated data structure you have ever created?
How do you dealwith team members that don't do their share of the work? Specific examples.
What are yourcarrer and education goals?
What do you hopeto get out of or learn from this job?
Have you checkedout our web page?
What is yourfavorite / worst course this term?
Why are youinterested in working at our company?
Do you have aweb page? What kind of things are on it?
What is classhierachi?
What is amessage map in MFC?
How would youprint out a singly linked list backwards?
Answer: UseRecursion:
void Reverse(Node *node)
{
if(node->next != NULL)
Reverse(node);
cout <<node->value << endl;
}
Is using the newoperator fast or slow and why?
How does stackmemory allocation work?
What are classesused for?
1) Code reuse.
2) Similar toreal world.
Why should Ihire you over the other people being interviewed?
Write the codefor a function with the following prototype:
isSubstring(char * source, char * substring);
What test caseswould you use to test it?
What is theoutput of, int *p = "foo"; cout << sizeof (p) << endl;
Write the codeto bit shift the variable, int shift = 4; the bits to the right.
What is thehexadecimal representation of the largest integer in a 32 bit system? Thesmallest integer.
What is thepurpose of the -> operator in C++? (cs342 page8)
What is thedifference between public, private and protected in C++? (page 572 C++ book)
What is onething that Java has that C++ does not? Answer: Garbage Collection
What is a thingC++ has that Java does not? Answer: Preprocessor
Why might youwant to use a Java application vs a Java applet?


0 comments:

Post a Comment