Introduction
You maybe a great programmer who uses C/C++ everyday but if you really want that 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 you should know the answers to if you are applying for any C++ position. At the end of the article, I have also added some links to sites to help you prepare for your interview.
What is the
difference between C and C++ ? Would you prefer to use one over the other ?
C is based on structured programming whereas C++ supports the object-oriented programming paradigm.Due to the advantages inherent in object-oriented programs such as modularity and reuse, C++ is preferred. However almost anything that can be built using C++ can also be built using C.
C is based on structured programming whereas C++ supports the object-oriented programming paradigm.Due to the advantages inherent in object-oriented programs such as modularity and reuse, C++ is preferred. However almost anything that can be built using C++ can also be built using C.
What are the
access privileges in C++ ? What is the default access level ?
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class 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.
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class 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 data
encapsulation ?
Data
Encapsulation is also known as data hiding. The most important advantage of
encapsulation is that it lets the programmer create an object and then provide
an interface to the object that other objects can use to call the methods
provided by the object. The programmer can change the internal workings of an
object but this transparent to other interfacing programs as long as the
interface remains unchanged.
What is
inheritance ?
Inheritance is
the process of deriving classes from other classes. In such a case, the
sub-class has an 'is-a' relationship with the super class. For e.g. vehicle can
be a super-class and car can be a sub-class derived from vehicle. In this case
a car is a vehicle. The super class 'is not a' sub-class as the sub-class is
more specialized and may contain additional members as compared to the super
class. The greatest advantage of inheritance is that it promotes generic design
and code reuse.
What is multiple
inheritance ? What are it's advantages and disadvantages ?
Multiple
Inheritance is the process whereby a sub-class can be derived from more than
one super class. The advantage of multiple inheritance is that it allows a class
to inherit the functionality of more than one base class thus allowing for
modeling of complex relationships. The disadvantage of multiple inheritance is
that it can lead to a lot of confusion when two base classes implement a method
with the same name.
What is
polymorphism?
Polymorphism
refers to the ability to have more than one method with the same signature in
an inheritance hierarchy. The correct method is invoked at run-time based on
the context (object) on which the method is invoked. Polymorphism allows for a
generic use of method names while providing specialized implementations for
them.
What do the
keyword static and const signify ?
When a class member is declared to be of a static type, it means that the member is not an instance variable but a class variable. Such a member is accessed using Classname.Membername (as opposed to Object.Membername). Const is a keyword used in C++ to specify that an object's value cannot be changed.
When a class member is declared to be of a static type, it means that the member is not an instance variable but a class variable. Such a member is accessed using Classname.Membername (as opposed to Object.Membername). Const is a keyword used in C++ to specify that an object's value cannot be changed.
How is memory
allocated/deallocated in C ? How about C++ ?
Memory is allocated in C using malloc() and freed using free(). In C++ the new() operator is used to allocate memory to an object and the delete() operator is used to free the memory taken up by an object.
Memory is allocated in C using malloc() and freed using free(). In C++ the new() 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 OO problem spaces and solutions.
UML refers to Unified Modeling Language. It is a language used to model OO problem spaces and solutions.
What is the
difference between a shallow copy and a deep copy ?
A shallow copy
simply creates a new object and inserts in it references to the members of the
original object. A deep copy constructs a new object and then creates in it
copies of each of the members of the original object.
Here are some
more interesting references on C++ interview preparation: be sure to check them
out before your next interview. Good Luck!
The C++ Interview
These 40 questions and answers will help
you land the assignment
by Alex Bykov
How do you rank
your C++ skills on a scale of 1 to 10?
This is often
the first question you will hear on an interview for a C++ contract. You will
be tempted to rate yourself high, and you should. This is your chance to
convince the client that you are just what he is looking for--an assertive and
knowledgeable professional who will be productive either working on a team or
on your own. Naturally, though, you should be able to support the ranking you
gave yourself by doing well on the interview. This article will help you
prepare for your C++ interview.
I put together a
list of 40 questions that I have had to answer during numerous technical
interviews in the past few years. You, too, will have to answer at least some
of them during an interview. Even if you use C++ on a daily basis, it pays to
go through the questions. Most of us, no matter how experienced, use only a
segment of the language that we are most comfortable with. Brief answers are
included, but you can find more information in the references
listed.
Q1. Is there
anything you can do in C++ that you cannot do in C?
A1. No. There is
nothing you can do in C++ that you cannot do in C. After all you can write a
C++ compiler in C.
Q2. What is
the difference between C++ structure and C++ class?
A2. The default
access level assigned to members of struct is public while the default access
level assigned to a class is private.
Q3. What is
encapsulation?
A3. Encapsulation
is welding of code and data together into objects.
Q4. What is
inheritance?
A4. Inheritance is
a mechanism through which a subclass inherits the properties and behavior of
its superclass.
Q5. What is
polymorphism?
A5. In Greek this
means "many shapes." As a consequence of inheritance and virtual
functions, a single task (for example, drawing a geometrical shape) can be
implemented using the same name (like draw()) and implemented differently (via
virtual functions) as each type in object hierarchy requires(circle.draw() or
rectangle.draw()). Later, when a polymorphic object (whose type is not known at
compile time) executes the draw() virtual function, the correct implementation
is chosen and executed at run time.
Q6. What
would you say if you saw "delete this" while reviewing your peer's
code?
A6. You should
never do this. Since compiler does not know whether the object was allocated on
the stack or on the heap, "delete this" could cause a disaster.
Q7. What is
the difference between public, protected, and private members of a class?
A7. Private members
are accessible only by members and friends of the class. Protected members are
accessible by members and friends of the class and by members and friends of
derived classes. Public members are accessible by everyone.
Q8. What is
the difference between non-virtual and virtual functions?
A8. The behavior of
a non-virtual function is known at compile time while the behavior of a virtual
function is not known until the run time.
Q9. What is a
pure virtual function?
A9. "A pure
virtual function is a function declared in a base class that has no definition
relative to the base."
Q10. What is
an abstract base class?
A10. It is a class
that has one or more pure virtual functions.
Q11. What is
the 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 an
object of class MyClass by value.
Q12. How do
you know that your class needs a virtual destructor?
A12. If your class
has at least one virtual function, you should make a destructor for this class
virtual. This will allow you to delete a dynamic object through a pointer to a
base class object. If the destructor is non-virtual, then wrong destructor will
be invoked during deletion of the dynamic object.
Q13. Why were
the templates introduced?
A13. Many data
structures and algorithms can be defined independently of the type of data they
work with. You can increase the amount of shared code by separating
data-dependent portions from data-independent portions, and templates were
introduced to help you do that.
Q14. What is
a static member of a class?
A14. Static data
members exist once for the entire class, as opposed to non-static data members,
which exist individually in each instance of a class.
Q15. What
feature of C++ would you use if you wanted to design a member function that
guarantees to leave "thisÓ object unchanged?
A15. It is
"const" as in: "int MyFunc (int test) const;"
Q16. Can you
overload a function based only on whether a parameter is a value or a
reference?
A16. No. Passing by
value and by reference looks identical to the caller.
Q17. What is
the difference between function overloading and function overriding?
A17. Overloading is
a method that allows defining multiple member functions with the same name but
different signatures. The compiler will pick the correct function based on the signature.
Overriding is a method that allows the derived class to redefine the behavior
of member functions which the derived class inherits from a base class. The
signatures of both base class member function and derived class member function
are the same; however, the implementation and, therefore, the behavior will
differ.
Q18. Can
derived class override some but not all of a set of overloaded virtual member
functions inherited from the base class?
A18. Compiler will
allow this, but it is a bad practice since overridden member functions will
hide all of the inherited overloads from the base class. You should really
override all of them.
Q19. What is
the difference between assignment and initialization in C++?
A19. Assignment
changes 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 are
copy constructors called?
A20. Copy
constructors are called in three cases: when a function returns an object of
that class by value, when the object of that class is passed by value as an
argument to a function, and, finally, when you construct an object based on
another object of the same class (Circle c1=c2;).
Q21. Why do
you have to provide your own copy constructor and assignment operator for
classes with dynamically allocated memory?
A21. If you don't,
the compiler will supply and execute the default constructor and the assignment
operator, but they will not do the job correctly. The default assignment
operator does memberwise assignment and the default copy constructor does
memberwise copy. In both cases you will only assign and manipulate pointers to
dynamic memory, which will lead to memory leaks and other abnormalities. You
should write your own assignment operator and copy constructor, which would
copy the pointer to memory so that each object has its own copy.
Q22. Does
compiler guarantee that initializers will be executed in the same order as they
appear on the initialization list?
A22. No. C++
guarantees that base class subobjects and member objects will be destroyed in
the opposite order from which they were constructed. This means that
initializers are executed in the order, which supports the above-mentioned
guarantee.
Q23. What is
function's signature?
A23. Function's
signature is its name plus the number and types of the parameters it accepts.
Q24. What
does extern "C" int func(int *, Foo) accomplish?
A24. It will turn
off "name mangling" for this function so that one can link to code
compiled by C compiler.
Q25. Why do
C++ compilers need name mangling?
A25. Name mangling
is the rule according to which C++ changes function's name into function
signature before passing that function to a linker. This is how the linker
differentiates between different functions with the same name.
Q26. What is
the difference between a pointer and a reference?
A26. A reference
must always refer to some object and, therefore, must always be initialized;
pointers do not have such restrictions. A pointer can be reassigned to point to
different objects while a reference always refers to an object with which it
was initialized.
Q27. How can
you access the static member of a class?
A27.
<ClassName>::<StaticMemberName>.
Q28. How are
prefix and postfix versions of operator++() differentiated?
A28. The postfix
version of operator++() has a dummy parameter of type int. The prefix version
does not have dummy parameter.
Q29. What
functions does C++ silently write and call?
A29. Constructors,
destructors, copy constructors, assignment operators, and address-of operators.
Q30. What is
the difference between new/delete and malloc/free?
A30. Malloc/free do
not know about constructors and destructors. New and delete create and destroy
objects, while malloc and free allocate and deallocate memory.
Q31. What is
the difference between delete and delete[ ]?
A31. Delete deletes
one object; delete[ ] deletes an array of objects.
Q32. Name two
cases where you MUST use initialization list as opposed to assignment in
constructors.
A32. Both non-static
const data members and reference data members cannot be assigned values;
instead, you should use initialization list to initialize them.
Q33. What is
the difference between const char *myPointer and char *const myPointer?
A33. Const char
*myPointer is a non constant pointer to constant data; while char *const
myPointer is a constant pointer to non constant data.
Q34. Suppose
that objects A, B, and C are instances of class MyClass (MyClass A, B, C;). How
should you design an assignment operator so that the "A=B=C;"
statement would be allowed by a compiler but "(A=B)=C;" would not be
allowed by a compiler?
A34. Make
operator=return a reference to a const object.
Q35. Is there
any problem with the following: char *a=NULL; char& p = *a;?
A35. The result is
undefined. You should never do this. A reference must always refer to some
object.
Q36. Class B
is derived from class A. Function f is A's friend. Is f B's friend as well?
A36. No. Friendship
cannot be inherited.
Q37. What
issue do auto_ptr objects address?
A37. If you use
auto_ptr objects you would not have to be concerned with heap objects not being
deleted even if the exception is thrown.
Q38. What
happens when a function throws an exception that was not specified by an
exception specification for this function?
A38. Unexpected() is
called, which, by default, will eventually trigger abort().
Q39. Why
should you prefer throw/catch mechanism to setjmp/longjmp?
A39. The main
problem with longjmp() is that it does not destroy local objects properly.
Q40. Can you
think of a situation where your program would crash without reaching the
breakpoint which you set at the beginning of main()?
A40. C++ allows for
dynamic initialization of global variables before main() is invoked. It is
possible that initialization of global will invoke some function. If this
function crashes the crash will occur before main() is entered.
If you feel
comfortable answering these questions, then rest assured that your chances of
impressing any interviewer are very high. Be prepared to know basic computer
science concepts such as data structures, search and sort algorithms, basic
database concepts, etc. The client's needs will determine what particular branch
of computer science you have to be familiar with, but you should always be
ready to implement the stock, the queue, and the linked list data structures
with either C or C++ programming languages. And know how to write your own
version of strcpy (string copy) in C programming language since very often they
ask you to do that.
Microsoft
Interview Questions & Answers
I recently
visited Microsoft's Silicon Valley
campus and interviewed with the Hotmail
group. If you've never had a Microsoft interview, realize that they are very
different than the standard interview. You won't be asked any of those
questions like, "What is your greatest weakness," or, "Where do
you want to be in five years?" Rather, a Microsoft interview typically contains
a number of brain teasers and coding questions. In fact, you can read interview questions from my internship
interviews.
Here are the
questions 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 you
want to immediately know the answer! Anyway, here goes:
Question: How could you
determine if a linked list contains a cycle in it, and, at what node the cycle
starts?
Answer: There are a
number of approaches. The approach I shared is in time N (where N is the number
of nodes in your linked list). Assume that the node definition contains a
boolean flag, bVisited.
struct Node { ...
bool bVisited; };
|
Then, to
determine whether a node has a loop, you could first set this flag to false for all of the
nodes:
// 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, to
determine whether or not a cycle existed, loop through each node. After
visiting a node, set bVisited to true. When you first
visit 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 better
approach was submitted by 4Guys visitor George R., a Microsoft
interviewer/employee. He recommended using the following technique, which is in
time O(N) and space O(1).
Use
two 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 moving
through the list twice as fast as p1. If the list is circular, (i.e. a cycle exists) it
will eventually get around to that sluggard, p1.
Thanks George!
Question: How would you
reverse a doubly-linked list?
Answer: This problem
isn't too hard. You just need to start at the head of the list, and iterate to
the end. At each node, swap the values of pNext and pPrev. Finally, set pHead to the last
node 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 have
an array that contains a number of strings (perhaps char * a[100]). Each string
is a word from the dictionary. Your task, described in high-level terms, is to
devise a way to determine and display all of the anagrams within the array (two
words are anagrams if they contain the same characters; for example, tales and slate are anagrams.)
Answer: Begin by
sorting each element in the array in alphabetical order. So, if one element of
your array was slate, it would be
rearranged to form aelst (use some
mechanism to know that the particular instance of aelst maps to slate). At this
point, you slate and tales would be
identical: aelst.
Next, sort the
entire array of these modified dictionary words. Now, all of the anagrams are
grouped together. Finally, step through the array and display duplicate terms,
mapping the sorted letters (aelst)
back to the word (slate or tales).
Question: Given the
following prototype:
int compact(int * p, int
size);
|
write a function
that 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 an
array 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 loop
will 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's
Journal
Spring 1998
By Al Stevens
Al, a
contributing editor for Dr. Dobb's Journal, can be contacted at
astevens@ddj.com.
In my August
1996 Dr. Dobb's Journal "C Programming" column, I reported
that someone with two to five years experience programming C++ can, according
to a report in ComputerWorld, command $70,000 on either coast and
$65,000 in the central part of the country. The opportunities seem even better
for 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, no
one expects the typical college graduate to have two or more years of solid
experience programming a particular platform. The range of your experience
depends on how your time was distributed between the usual class workload, lab
time, research projects, and any part-time jobs you might have had.
Nonetheless, there is a demand for qualified people and a shortage of qualified
people. Employers will be looking to entry-level recent graduates to take up
the slack. That's where you come in. You'll be competing with all those other
grads for those jobs, and, if the ComputerWorld report is a forecast of
what's coming, in two years, this summer's entry-level programmers will be the
veterans knocking down those respectable salaries. The trick is to get your foot
in the door now. Let's see if we can help prepare you to impress the folks who
are interviewing new programmers.
Windows NT
programming is Win32 programming, which, unless you are writing deep
systems-level code, is the same thing as Windows 95 programming. If you don't
have 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 there
are a few things you can do to prepare to demonstrate an understanding of the
programming environments that employers want to discuss. That demonstration
could be just the advantage that edges out the competition.
You need to show
in a brief interview that you understand and can work with C++ in the Win32
development environment. Those are two different curves, both of which are
steep. Let's start with C++.
I put together a
list of questions that employers can ask potential programming employees to
qualify them as to the extent of their C++ knowledge. These, I think, are
representative of the kinds of things that you will be asked. I published the
questions and my opinions about appropriate answers in my column. From the
response I got from readers, I learned that many practicing C++ programmers
cannot 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 a
rut, using a comfortable subset of the language, and, as a consequence, were
not using C++ to its full potential. Other readers suggested more questions and
a broader approach to qualifying an applicant. Those suggestions caused me to
evaluate my approach and adjust it.
I divided
applicants into three groups: those who understand C++ well enough to use it as
an improved C; those who have experience designing C++ classes; and those who
are so motivated that they keep up with the recently approved specification of
standard C++.
I will state
here 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 the
tutorials 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 that
statement to be a shameless plug, then you fully understand my motives. It's
true, nonetheless. Let's get on with it.
A lot of what
follows was taken directly from my August and September 1996 "C
Programming" columns in Dr. Dobb's Journal. I reworded some of it
to reflect your concerns and to incorporate some changes and corrections that
other readers sent to me.
Questions for All C++ Applicants
Here's the first
group of C++ questions and my opinions about what some acceptable answers would
be. These questions do not cover C++ wall-to-wall, of course. I selected them
as being typical of the kinds of things that all C++ programmers should be
expected to know. There are five questions. Three correct answers is a good
score.
Q: How do you link
a C++ program to C functions?
A: By using the extern
"C" linkage specification around the C function declarations.
You should know
about mangled function names and type-safe linkages. Then you should explain
how the extern "C" linkage specification statement turns that
feature off during compilation so that the linker properly links function calls
to C functions. Another acceptable answer is "I don't know. We never had
to do that." Merely describing what a linker does would indicate to me that
you do not understand the issue that underlies the question.
Q: Explain the
scope resolution operator.
A: The scope
resolution operator permits a program to reference an identifier in the global
scope that has been hidden by another identifier with the same name in the
local scope.
The answer can
get complicated. It should start with "colon-colon," however. (Some
readers had not heard the term, "scope resolution operator," but they
knew what :: means. You should know the formal names of such things so that you
can understand all communication about them.) If you claim to be well into the
design or use of classes that employ inheritance, you tend to address
overriding virtual function overrides to explicitly call a function higher in
the hierarchy. That's good knowledge to demonstrate, but address your comments
specifically to global scope resolution. Describe C++'s ability to override the
particular C behavior where identifiers in the global scope are always hidden
by similar identifiers in a local scope.
Q: What are the
differences between a C++ struct and C++ class?
A: The default
member and base class access specifiers are different.
This is one of
the commonly misunderstood aspects of C++. Believe it or not, many programmers
think that a C++ struct is just like a C struct, while a C++ class
has inheritance, access specifiers, member functions, overloaded operators,
and so on. Some of them have even written books about C++. Actually, the C++ struct
has all the features of the class. The only differences are that a struct
defaults to public member access and public base class inheritance, and a class
defaults to the private access specifier and private base class
inheritance. Getting this question wrong does not necessarily disqualify you
because you will be in plenty of good company. Getting it right is a definite
plus.
Q: How many ways
are there to initialize an int with a constant?
A: Two.
There are two
formats for initializers in C++ as shown in Example
1. Example 1(a) uses the
traditional 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 know
about 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 prefer
it.
A reader wrote
to tell me of two other ways, as shown in Examples
2(a) and 2(b), which made me think that maybe the answer could be
extended even further to include the initialization of an int function
parameter with a constant argument from the caller.
Q: How does
throwing and catching exceptions differ from using setjmp and longjmp?
A: The throw
operation calls the destructors for automatic objects instantiated since entry
to the try block.
Exceptions are
in the mainstream of C++ now, so most programmers, if they are familiar with setjmp
and longjmp, should know the difference. Both idioms return a program
from the nested depths of multiple function calls to a defined position higher
in the program. The program stack is "unwound" so that the state of
the program with respect to function calls and pushed arguments is restored as
if the calls had not been made. C++ exception handling adds to that behavior
the orderly calls to the destructors of automatic objects that were
instantiated as the program proceeded from within the try block toward where
the throw expression is evaluated.
It's okay to
discuss the notational differences between the two idioms. Explain the syntax
of try blocks, catch exception handlers, and throw expressions. Then
specifically address what happens in a throw that does not happen in a longjmp.
Your answer should reflect an understanding of the behavior described in the
answer just given.
One valid reason
for not knowing about exception handling is that your experience is exclusively
with older C++ compilers that do not implement exception handling. I would
prefer that you have at least heard of exception handling, though.
It is not
unusual for C and C++ programmers to be unfamiliar with setjmp/ longjmp.
Those constructs are not particularly intuitive. A C programmer who has written
recursive descent parsing algorithms will certainly be familiar with setjmp/
longjmp. Others might not, and that's acceptable. In that case, you won't
be able to discuss how setjmp/longjmp differs from C++ exception
handling, but let the interview turn into a discussion of C++ exception
handling in general. That conversation will reveal to the interviewer a lot
about your overall understanding of C++.
Questions for Class Designers
The next group
of questions explores your knowledge of class design. There are eight
questions. Five out of eight is a good score.
Q: What is your
reaction to this line of code?
delete
this;
A: It's not a good
practice.
A good
programmer will insist that the statement is never to be used if the class is
to be used by other programmers and instantiated as static, extern, or
automatic objects. That much should be obvious.
The code has two
built-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 the
delete statement executes. There is no portable way for an object to tell that
it was instantiated on the heap, so the class cannot assert that its object is
properly instantiated. Second, when an object commits suicide this way, the
using program might not know about its demise. As far as the instantiating
program is concerned, the object remains in scope and continues to exist even
though the object did itself in. Subsequent dereferencing of the pointer can
and usually does lead to disaster.
A reader pointed
out that a class can ensure that its objects are instantiated on the heap by
making its destructor private. This idiom necessitates a kludgy DeleteMe
kind of function because the instantiator cannot call the delete operator for
objects of the class. The DeleteMe function would then use "delete
this."
I got a lot of
mail about this issue. Many programmers believe that delete this is a
valid construct. In my experience, classes that use delete this when
objects are instantiated by users usually spawn bugs related to the idiom, most
often when a program dereferences a pointer to an object that has already
deleted itself.
Q: What is a
default constructor?
A: A constructor
that has no arguments or one where all the arguments have default argument
values.
If you don't
code a default constructor, the compiler provides one if there are no other
constructors. If you are going to instantiate an array of objects of the class,
the class must have a default constructor.
Q: What is a
conversion constructor?
A: A constructor
that accepts one argument of a different type.
The compiler
uses this idiom as one way to infer conversion rules for a class. A constructor
with more than one argument and with default argument values can be interpreted
by the compiler as a conversion constructor when the compiler is looking for an
object of the type and sees an object of the type of the constructor's first
argument.
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.
First, you must
know that a copy constructor is one that has only one argument, which is a
reference to the same type as the constructor. The compiler invokes a copy
constructor wherever it needs to make a copy of the object, for example to pass
an argument by value. If you do not provide a copy constructor, the compiler
creates a member-by-member copy constructor for you.
You can write
overloaded assignment operators that take arguments of other classes, but that
behavior is usually implemented with implicit conversion constructors. If you
do not provide an overloaded assignment operator for the class, the compiler
creates a default member-by-member assignment operator.
This discussion
is a good place to get into why classes need copy constructors and overloaded
assignment operators. By discussing the requirements with respect to data
member pointers that point to dynamically allocated resources, you demonstrate
a good grasp of the problem.
Q: When should you
use multiple inheritance?
A: There are
three acceptable answers: "Never," "Rarely," and "When
the problem domain cannot be accurately modeled any other way."
There are some
famous C++ pundits and luminaries who disagree with that third answer, so be
careful.
Let's digress to
consider this issue lest your interview turn into a religious debate. Consider
an Asset class, Building class, Vehicle class, and CompanyCar
class. All company cars are vehicles. Some company cars are assets because the
organizations own them. Others might be leased. Not all assets are vehicles.
Money accounts are assets. Real-estate holdings are assets. Some real-estate
holdings are buildings. Not all buildings are assets. Ad infinitum. When you
diagram these relationships, it becomes apparent that multiple inheritance is
an intuitive way to model this common problem domain. You should understand,
however, that multiple inheritance, like a chainsaw, is a useful tool that has
its perils, needs respect, and is best avoided except when nothing else will
do. Stress this understanding because your interviewer might share the common
bias against multiple inheritance that many object-oriented designers hold.
Q: What is a
virtual destructor?
A: The simple
answer is that a virtual destructor is one that is declared with the virtual
attribute.
The behavior of
a virtual destructor is what is important. If you destroy an object through a
pointer or reference to a base class, and the base-class destructor is not
virtual, the derived-class destructors are not executed, and the destruction
might not be complete.
Q: Explain the ISA
and HASA class relationships. How would you implement each in a class design?
A: A specialized
class "is a" specialization of another class and, therefore, has the
ISA relationship with the other class. An Employee ISA Person.
This relationship is best implemented with inheritance. Employee is derived
from Person. A class may have an instance of another class. For example,
an Employee "has a" Salary, therefore the Employee
class has the HASA relationship with the Salary class. This relationship
is best implemented by embedding an object of the Salary class in the Employee
class.
The answer to
this question reveals whether you have an understanding of the fundamentals of
object-oriented design, which is important to reliable class design.
There are other
relationships. The USESA relationship is when one class uses the services of
another. The Employee class uses an object (cout) of the ostream
class to display the employee's name onscreen, for example. But if you get ISA
and HASA right, you usually don't need to go any further.
Q: When is a
template a better solution than a base class?
A: When you are
designing a generic class to contain or otherwise manage objects of other
types, when the format and behavior of those other types are unimportant to
their containment or management, and particularly when those other types are
unknown (thus the genericity) to the designer of the container or manager class.
Prior to
templates, you had to use inheritance; your design might include a generic List
container class and an application-specific Employee class. To put
employees in a list, a ListedEmployee class is multiply derived
(contrived) from the Employee and List classes. These solutions
were unwieldy and error-prone. Templates solved that problem.
Questions for ANSI-Knowledgeable
Applicants
There are six
questions for those who profess knowledge of the progress of the ANSI
committee. If you claim to have that much interest in the language, you should
know the answers to all these questions.
Q: What is a
mutable member?
A: One that can be
modified by the class even when the object of the class or the member function
doing the modification is const.
Understanding
this requirement implies an understanding of C++ const, which many
programmers do not have. I have seen large class designs that do not employ the
const qualifier anywhere. Some of those designs are my own early C++
efforts. One author suggests that some programmers find const to be such
a bother that it is easier to ignore const than to try to use it
meaningfully. No wonder many programmers don't understand the power and
implications of const. Someone who claims to have enough interest in the
language and its evolution to keep pace with the ANSI deliberations should not
be ignorant of const, however.
Q: What is an
explicit constructor?
A: A conversion
constructor declared with the explicit keyword. The compiler does not
use an explicit constructor to implement an implied conversion of types. Its
purpose is reserved explicitly for construction.
Q: What is the
Standard Template Library?
A: A library of
container templates approved by the ANSI committee for inclusion in the
standard C++ specification.
An applicant who
then launches into a discussion of the generic programming model, iterators,
allocators, algorithms, and such, has a higher than average understanding of
the new technology that STL brings to C++ programming.
Q: Describe
run-time type identification.
A: The ability to
determine at run time the type of an object by using the typeid operator
or the dynamic_cast operator.
Q: What problem
does the namespace feature solve?
A: Multiple
providers of libraries might use common global identifiers causing a name
collision when an application tries to link with two or more such libraries.
The name-space feature surrounds a library's external declarations with a
unique namespace that eliminates the potential for those collisions.
This solution
assumes that two library vendors don't use the same namespace, of course.
Q: Are there any
new intrinsic (built-in) data types?
A: Yes. The ANSI
committee added the bool intrinsic type and its true and false value
keywords and the wchar_t data type to support character sets wider than
eight bits.
Other apparent
new types (string, complex, and so forth) are implemented as
classes in the Standard C++ Library rather than as intrinsic types.
In my original
column, 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 even
I would not have scored 100 percent on my own test.
Understanding Win32
I haven't put
together a list of questions that you should know about the Win32 API because
the subject is way too broad to cover that way. There's no way that I could
guess what an interviewer is likely to ask. Instead, I'm going to tell you how
to become expert enough to get through an interview. You'll have to cram this
work into your otherwise busy student's schedule. I don't know how to tell you
where to find the time, but if you can do it, it's worth it. Forsake the social
life 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 are
investing in your future, and this might be the most profitable time you'll
ever spend. Don't, of course, neglect your other studies.
You'll need a
Windows 95 (or NT) system with Visual C++. Run the tutorials that the VC++
online books include. Get comfortable with the programming environment -- the
editor, the debugger, the online documentation, the class wizard, the resource
editor, and so on.
Next, you need
two good books about Windows and MFC programming. These books are the classic Programming
Windows 95, by Charles Petzold, and Programming Windows 95 with MFC,
by Jeff Prosise (both published by Microsoft Press). Read the Petzold book
cover to cover. Do it at your computer and run the programs that Charles
includes. Step through them with the VC++ debugger. Get a solid foundation in
the Win32 API, the Windows event-driven, message-based programming model, and
the Windows way of using resources -- menus, dialog boxes, controls, and so on.
Now, read
Prosise. Learn the MFC application/document/view architecture. Learn how the
MFC class library encapsulates those things and the Windows resources. Run all
of Jeff's programs with the debugger just as you did Charles's. Be aware that
the debugger steps into all the MFC code. If you find yourself in the depths of
an MFC constructor, for example, use the "Step out of" command to get
back to the example. Eventually you'll learn to anticipate that and step over
statements that would lead you into the vapor.
Here's the best
advice I can give you. With both these books, when you are running the example
programs through the debugger, never step out of a line of code until you fully
understand what the line of code is doing and why. If the book is unclear about
it, and if, after wracking your brain and exhausting all your resources, you
can't figure it out, send me a message at astevens@ddj.com. If I can't figure
it out, I'll find someone who can.
This offer is
good until December 24, 1999. If you don't have a job by then, you can have
mine, because that's when I plan to get out of this business to avoid the Year
2000 fiasco.
How to Comport Yourself in the Interview
Bear with me now
while I patronize you for a moment. I've sat through enough interviews to know
what rings the chimes of an interviewer and what turns them cold. This is going
to be like one of those motivational speeches that people buy on cassettes from
late night TV pitchmen. Inasmuch as you already paid for the magazine, consider
this one to be free.
Remember, no one
expects you to demonstrate the breadth of experience and judgement that comes
with years of experience. You should not be expected to know the relative
merits of every compiler, operating system, application framework, and so on.
You should know what those things are, and, being a smart young person, you are
expected to have and voice strong opinions based on your limited experience,
but those opinions need not demonstrate anything more than the youthful
exuberance and enthusiasm to which you are naturally entitled. You are bullet-proof,
beer is food, and all's right with the world.
Relax in the
interview and be yourself. It is not an adversarial situation. The company
really wants you to be the one. Most of us hate interviewing and hope above
hope that the right person shows up in the first session so we can get out of
having to do any more interviews.
Above all, don't
pretend 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 the
chance, you can learn whatever you lack in plenty of time to be of useful
service to the company. Most programming is intuitive to someone like yourself
who has the aptitude. Make them know that you understand that concept and can
apply it. The successful applicant is assured and confident. Make the
interviewer feel that by hiring you, the company will solve its programming
problems.
Here's what else
not to do. I know I just told you to be yourself, but, please, avoid making
social and political statements with your appearance. You have no way of
knowing what the interviewer's biases and prejudices are, and that's the person
whose muster you must pass today, even if on the job you'd never see that person
again. Sometimes the initial screening is done by personnel types who wouldn't
know a byte if it bit them. Dress and groom yourself neatly and neutrally. Try
to look capable and professional. You can retreat to your own style, slob or
fop, after you get the job and prove your worth.
Express a
willingness to relocate anywhere and work long hours on any kind of
application. 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 what
you do best and that's what they need most. Emphasize that you want to work
with the best technical people that the company has so that you can learn.
Interviewers like to hear that.
Finally, don't
get discouraged. You won't get an offer for every interview, and you'll get
some offers that are unacceptable. Keep your spirits up, apply for every job that
looks appealing, and spend your evenings sharpening your programming skills at
home. If you see a job that you want, don't be dissuaded by an imposing list of
qualifications that you do not possess. Chances are, the company won't find
anyone with all the right skills anyway. Go for it and convince the
interviewers that you can learn what you need to know.
Do these things
and the right job will find you.
C++ Questions
·
What
are the major differences between C and C++?
·
What
are the differences between new
and malloc?
·
What
is the difference between delete
and delete[]?
·
What
are the differences between a struct in C and in C++?
·
What
are the advantages/disadvantages of using #define?
·
What
are the advantages/disadvantages of using inline and const?
·
What
is the difference between a pointer and a reference?
·
When
would you use a pointer? A reference?
·
What
does it mean to take the address of a reference?
·
What
does it mean to declare a function or variable as static?
·
What
is the order of initalization for data?
·
What
is name mangling/name decoration?
·
What
kind of problems does name mangling cause?
·
How
do you work around them?
·
What
is a class?
·
What
are the differences between a struct and a class in C++?
·
What
is the difference between public, private, and protected access?
·
For
class CFoo { }; what default
methods will the compiler generate for you>?
·
How
can you force the compiler to not generate them?
·
What
is the purpose of a constructor? Destructor?
·
What
is a constructor initializer list?
·
When
must you use a constructor initializer list?
·
What
is a:
·
Constructor?
·
Destructor?
·
Default
constructor?
·
Copy
constructor?
·
Conversion
constructor?
·
What
does it mean to declare a...
·
member
function asvirtual?
·
member
function asstatic?
·
member
function asstatic?
·
member
varible as static?
·
destructor
as static?
·
Can
you explain the term "resource acqusition is initialization?"
·
What
is a "pure virtual" member function?
·
What
is the difference between public, private, and protected inheritance?
·
What
is virtual inheritance?
·
What
is placement new?
·
What
is the difference between operator new and the new operator?
·
What
is exception handling?
·
Explain
what happens when an exception is thrown in C++.
·
What
happens if an exception is not caught?
·
What
happens if an exception is throws from an object's constructor?
·
What
happens if an exception is throws from an object's destructor?
·
What
are the costs and benefits of using exceptions?
·
When
would you choose to return an error code rather than throw an exception?
·
What
is a template?
·
What
is partial specialization or template specialization?
·
How
can you force instantiation of a template?
·
What
is an iterator?
·
What
is an algorithm (in terms of the STL/C++ standard library)?
·
What
is std::auto_ptr?
·
What
is wrong with this statement? std::auto_ptr ptr(new char[10]);
·
It
is possible to build a C++ compiler on top of a C compiler. How would you do
this? (Note: I've only asked this question once; and yes, he understood that I
was asking him how cfront was put together. We hired him.)/i>
Code Snippets
I like to put
these up on a whiteboard, and ask questiosn about them.
What output does
the following code generate? Why?
What output does it generate if you make A::Foo() a pure virtual function?
What output does it generate if you make A::Foo() a pure virtual function?
class
A {
A()
{ this->Foo(); }
virtual
void Foo() { cout << "A::Foo()" << endl; }
};
class
B : public A {
B()
{ this->Foo(); }
virtual
void Foo() { cout << "A::Foo()" << endl; }
};
int
main(int, char**)
{
A objectA;
B objectB;
return
0;
}
What output does
this program generate as shown? Why?
class
A {
A()
{ cout << "A::A()" << endl; }
~A()
{ cout << "A::~A()" << endl; throw
"A::exception"; }
};
class
B {
B()
{ cout << "B::B()" << endl; throw
"B::exception"; }
~B()
{ cout << "B::~B()"; }
};
int
main(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;
}
return
0;
}
Misc. Questions
·
What's
the difference between SQL, DDL, and DML?
·
What's
a join? An inner join? An outer join?
·
Describe
HTTP.
·
What's
a design pattern?
·
Can
you explain the singleton, vistor, facade, or handle class design pattern?
C++
Test / Typical Interview Questions
Check out the
following links for interview help.
http://www.collegegrad.com/intv/intrview.html
Level 2
What is the
output 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
void main ( void )
{
unsigned number = 100;
if (number > (unsigned) -1 )
printf("Hello");
else
printf("There");
}
Output : There
Reason : When -1 is
converted 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>
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 block of code
that follows is executed after the for loop is run 100 times.
Level 1
What is the output of the following code segment?
}
}
Output : 100
Reason : The for loop has a ";" at the end of it, so the block of 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 of retVale.
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 of retVale.
Level 3
What is the
output 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;
}
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.
tMult: 20
pVal GetValue() : 10
pVal2 GetData(): 20
Reason: See the definition of virtual member below.
What is the
result of the following bit shifting segment of code?
What is serialization?
Answer: Serialization is the process of storing the state of an object for the purpose of loading it at another time. When an object is serialized, information about the type of object is written to the storage along with information and data about the object. When an object is deserialized, the same process happens in reverse, and the object is loaded and created from the input stream.
What is a class?
A class allows data and functions to be bundled together and used as if they are a single element. Classes typically model real-world concepts that have both data and some sort of behavior.
A class allows data and functions to be bundled together and used as if they are a single element. Classes typically model real-world concepts that have both data and some sort of behavior.
What is an
instance of a class?
Answer: An
instance 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 your
programs.
Classes and
instances of classes are not the same things -- think of a class as the
description of an object; an instance of a class is a concrete occurrence of
that class.
What is the
difference between TCP/IP and UDP/IP?
TCP (Transport
Control Protocol ) and UDP ( user datagram protocal) are both methods of
transport protocols. IP stands for internet protocal. TCP/IP is like a
telephone connection for communication to take place there must be a sender and
receiver; there must be a connection made. UDP/IP does not require a connection
to be made, similar to the mail system. You can post a letter without someone
necessarily receiving it.
TCP/IP is
designed to solve modern computer communication problems by allowing different
computers to communicate across multiple networks.
IP or the
"Internet Protocol" will provide the thread that allows data to find
its way between two computers across multiple networks.
TCP or the
"Transport Control Protocol" will provide the "reliable
transport" or assurance that data is sent and received between the two
computers and their respective application programs.
What
is 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 the
following 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 binary
tree?
A binary tree is
an ordered tree in which each internal node has either zero or two children.
Some definitions allow for simply
What is a binary
search tree?
Each internal
node v stores an element e such that the elements stored in the left subtree of
v are less than or equal to e, and the elements stored in the right subtree of
v are greater than or equal to e.
Name two string
compression algorithms.
Huffman Coding
and
Name two pattern
matching algorithms.
Knuth-Morris-Pratt
Algorithm and Boyer-Moore Algorithm
All
Object Oriented Languages share three common defining traits explain these
Encapsulation,
Polymorphism, and Inheritence.
Inheritance
is the process by which one object can acquire the properties
of another, be more specific?
of another, be more specific?
An object can
inherit a general set of properties to which it can add those features that are
specific only to itself. Inheritance is important because it allows an object
to support the concept of hierarchical classification.
What is a
Virtual Member Function?
Calls to virtual
member 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 to
determine their own behavior at runtime - the chief characteristic of
polymorphism.
How many gas
stations are there in Canada?
What are you
strengths?
What are you
weaknesses or areas for improvement?
What is the most
complicated data structure you have ever created?
How do you deal
with team members that don't do their share of the work? Specific examples.
What are your
carrer and education goals?
What do you hope
to get out of or learn from this job?
Have you checked
out our web page?
What is your
favorite / worst course this term?
Why are you
interested in working at our company?
Do you have a
web page? What kind of things are on it?
What is class
hierachi?
What is a
message map in MFC?
How would you
print out a singly linked list backwards?
Answer: Use
Recursion:
void Reverse
(Node *node)
{
if
(node->next != NULL)
Reverse(node);
cout <<
node->value << endl;
}
Is using the new
operator fast or slow and why?
How does stack
memory allocation work?
What are classes
used for?
1) Code reuse.
2) Similar to
real world.
Why should I
hire you over the other people being interviewed?
Write the code
for a function with the following prototype:
isSubstring
(char * source, char * substring);
What test cases
would you use to test it?
What is the
output of, int *p = "foo"; cout << sizeof (p) << endl;
Write the code
to bit shift the variable, int shift = 4; the bits to the right.
What is the
hexadecimal representation of the largest integer in a 32 bit system? The
smallest integer.
What is the
purpose of the -> operator in C++? (cs342 page8)
What is the
difference between public, private and protected in C++? (page 572 C++ book)
What is one
thing that Java has that C++ does not? Answer: Garbage Collection
What is a thing
C++ has that Java does not? Answer: Preprocessor
Why might you
want to use a Java application vs a Java applet?
0 comments:
Post a Comment