Appendix A

C++ Interviews

Reading this book will surely give your C++ career a kick-start, but employers will want you to prove yourself before they offer the big bucks. Interview methodologies vary from company to company, but many aspects of technical interviews are predictable. A thorough interviewer will want to test your basic coding skills, your debugging skills, your design and style skills, and your problem-solving skills. The set of questions you might be asked is quite large. In this appendix, you’ll read about some of the different types of questions you may encounter and the best tactics for landing that high-paying C++ programming job you’re after.

This appendix iterates through the chapters of the book, discussing the aspects of each chapter that are likely to come up in an interview situation. Each section also includes a discussion of the types of questions that could be designed to test those skills, and the best ways to deal with those questions.

CHAPTER 1: A CRASH COURSE IN C++

A technical interview will often include some basic C++ questions to weed out the candidates who put C++ on their resume simply because they’ve heard of the language. These questions might be asked during a phone screen, when a developer or recruiter calls you before bringing you in for an in-person interview. They could also be asked via e-mail or in person. When answering these questions, remember that the interviewer is just trying to establish that you’ve actually learned and used C++. You generally don’t need to get every detail right to earn high marks.

Things to Remember

  • main() and its parameters
  • When you are applying for a platform specific job, check what kind of main() function and which parameters that platform might use, for example, on Windows, your program might use WinMain(), _tmain(), wmain(), and a few others.
  • Use of functions
  • Header file syntax, including the omission of “.h” for standard library headers
  • Basic use of namespaces
  • Language basics, such as loop syntax, the ternary operator, and variables
  • The difference between the stack and the heap
  • Dynamically allocated arrays
  • Use of const
  • What references are
  • The C++11 auto and decltype keywords

Types of Questions

Basic C++ questions will often come in the form of a vocabulary test. The interviewer may ask you to define C++ terms, such as const or static. He or she may be looking for the textbook answer, but you can often score extra points by giving sample usage or extra detail. For example, in addition to saying that one of the uses of const is to specify that a reference argument cannot be changed, you can also say that a const reference is more efficient than a copy when passing an object into a function or method.

The other form that basic C++ competence questions can take is a short program that you write in front of the interviewer. An interviewer may give you a warm-up question, such as, “Write Hello, World in C++.” When you get a seemingly simple question like this, make sure that you score all the extra points you can by showing that you are namespace-savvy, you use streams instead of printf(), and you know which standard headers to include.

CHAPTER 2: DESIGNING PROFESSIONAL C++ PROGRAMS

Your interviewer will want to make sure that in addition to knowing the C++ language, you are skilled at applying it. You may not be asked a design question explicitly, but good interviewers have a variety of techniques to sneak design into other questions, as you’ll see.

A potential employer will also want to know that you’re able to work with code that you didn’t write yourself. If you’ve listed specific libraries on your resume, you should be prepared to answer questions on those. If you didn’t list specific libraries, a general understanding of the importance of libraries will probably suffice.

Things to Remember

  • Design is subjective — be prepared to defend design decisions you make during the interview.
  • Recall the details of a design you’ve done in the past prior to the interview in case you are asked for an example.
  • Be prepared to define abstraction and give an example.
  • Be prepared to sketch out a design visually, including class hierarchies.
  • Be prepared to tout the benefits of code reuse.
  • The concept of libraries
  • The tradeoffs between building from scratch and reusing existing code
  • The basics of big-O notation, or at least remember that O(n log n) is better than O(n2)
  • The functionality that is included in the C++ Standard Library
  • The high-level definition of design patterns

Types of Questions

Design questions are hard for an interviewer to come up with — any program that you could design in an interview setting is probably too simple to demonstrate real-world design skills. Design questions may come in a more fuzzy form, such as, “Tell me the steps in designing a good program,” or “Explain the principle of abstraction.” They can also be less explicit. When discussing your previous job, the interviewer can say, “Can you explain the design of that project to me?”

If the interviewer is asking you about a specific library, he or she will probably focus on the high-level aspects of the library as opposed to technical specifics. For example, you can be asked to explain what the strengths and weaknesses of the STL are from a library design point of view. The best candidates talk about the STL’s breadth and standardization as strengths, and its steep learning curve as the major drawback.

You may also be asked a design question that initially doesn’t sound as if it’s related to libraries. For example, the interviewer could ask how you would go about creating an application that downloads MP3 music from the web and plays it on the local computer. This question isn’t explicitly related to libraries, but that’s what it’s getting at; the question is really asking about process.

You should begin by talking about how you would gather requirements and do initial prototypes. Because the question mentions two specific technologies, the interviewer would like to know how you would deal with them. This is where libraries come into play. If you tell the interviewer that you would write your own web classes and MP3 playing code, you won’t fail the test, but you will be challenged to justify the time and expense of reinventing these tools.

A better answer would be to say that you would survey existing libraries that perform web and MP3 functionality to see if one exists that suits the project. You might want to name some technologies that you would start with, such as libcurl for web retrieval in Linux or the Windows Media library for music playback in Windows.

Mentioning some websites with free libraries, and some ideas of what those websites provide, might also get you extra points. For example, www.codeguru.com and www.codeproject.com for Windows libraries; www.boost.org for C++ libraries; and www.sourceforge.org for Linux libraries. Explaining the major differences between some licenses, such as the GPL license, Boost license, Creative Commons license, CodeGuru license, OpenBSD license, and so on, might score you extra credit. Don’t stress GNU/GPL too much; you might get negative points because you might be seen as an active hazard to the company’s Intellectual Property (IP).

CHAPTER 3: DESIGNING WITH OBJECTS

Object-oriented design questions are used to weed out C programmers who merely know what a reference is, from C++ programmers who actually use the object-oriented features of the language. Interviewers don’t take anything for granted; even if you’ve been using object-oriented languages for years, they may still want to see evidence that you understand the methodology.

Things to Remember

  • The differences between the procedural and object-oriented paradigms
  • The differences between a class and an object
  • Expressing classes in terms of components, properties, and behaviors
  • Is-a and has-a relationships
  • The tradeoffs involved in multiple inheritance

Types of Questions

There are typically two ways to ask object-oriented design questions. You can be asked to define an object-oriented concept, or you can be asked to sketch out an object-oriented hierarchy. The former is pretty straightforward. Remember that examples might earn you extra credit.

If you’re asked to sketch out an OO hierarchy, the interviewer will usually provide a simple application, such as a card game, for which you should design a class hierarchy. Interviewers often ask design questions about games because they are applications with which most people are already familiar. They also help lighten the mood a bit when compared to questions about things like database implementations. The hierarchy you generate will, of course, vary based on the game or application they are asking you to design. Here are some points to consider:

  • The interviewer wants to see your thought process. Think aloud, brainstorm, engage the interviewer in a discussion, and don’t be afraid to erase and go in a different direction.
  • The interviewer may assume that you are familiar with the application. If you’ve never heard of Blackjack and you get a question about it, ask the interviewer to clarify or change the question.
  • Unless the interviewer gives you a specific format to use when describing the hierarchy, we recommend that your class diagrams take the form of inheritance trees with rough lists of methods and data members for each class.
  • You may have to defend your design or revise it to take added requirements into consideration. Try to gauge whether the interviewer sees actual flaws in your design, or whether she just wants to put you on the defensive to see your skills of persuasion.

CHAPTER 4: DESIGNING FOR REUSE

Interviewers rarely ask questions about designing reusable code. This omission is unfortunate because having programmers on staff who can write only single-purpose code can be detrimental to a programming organization. Occasionally, you’ll find a company that is savvy on code reuse and asks about it in their interviews. Such a question is an indication that it might be a good company to work for.

Things to Remember

  • The principle of abstraction
  • The creation of subsystems and class hierarchies
  • The general rules for good interface design, which are interfaces with only public methods and no implementation details
  • When to use templates and when to use inheritance

Types of Questions

Questions about reuse will almost certainly be about previous projects on which you have worked. For example, if you worked at a company that produced both consumer and professional video-editing applications, the interviewer may ask how code was shared between the two applications. Even if you aren’t explicitly asked about code reuse, you might be able to sneak it in. When you’re describing some of your past work, tell the interviewer if the modules you wrote were used in other projects. Even when answering apparently straight coding questions, make sure to consider and mention the interfaces involved.

CHAPTER 5: CODING WITH STYLE

Anybody who’s coded in the professional world has had a co-worker who codes as if they learned C++ from the back of a cereal box. Nobody wants to work with someone who writes messy code, so interviewers sometimes attempt to determine a candidate’s style skills.

Things to Remember

  • Style matters, even during interview questions that aren’t explicitly style related.
  • Well-written code doesn’t need extensive comments.
  • Comments can be used to convey metainformation.
  • The principle of decomposition
  • The principle of refactoring
  • Naming techniques

Types of Questions

Style questions can come in a few different forms. One of the authors was once asked to write the code for a relatively complex algorithm on a whiteboard. As soon as he wrote the first variable name, the interviewer stopped him and told him he passed. The question wasn’t about the algorithm; it was just a red herring to see how well he named his variables. More commonly, you may be asked to submit code that you’ve written, or to give your opinions on style.

You need to be careful when a potential employer asks you to submit code. You probably cannot legally submit code that you wrote for a previous employer. You also have to find a piece of code that shows off your skills without requiring too much background knowledge. For example, you wouldn’t want to submit your master’s thesis on high-speed image rendering to a company that is interviewing you for a database administration position.

If the company gives you a specific program to write, that’s a perfect opportunity to show off what you’ve learned in this book. How many other candidates will include unit tests with their program, or extensive comments? Even if the potential employer doesn’t specify the program, you should consider writing a small program specifically to submit to the company. Instead of selecting some code you’ve already written, start from scratch to produce code that is relevant to the job and highlights good style.

Also, if you have documentation that you have written and that can be released, meaning it is not proprietary, use it to show your skills to communicate, it will give you extra points. Websites you have built or maintained, articles you have submitted to places like CodeGuru, CodeProject, SourceForge, and so on, are very useful; it says you can not only write code, but you can communicate to others how to effectively use that code. Of course, having a book title attached to your name is also a big plus.

CHAPTERS 6 AND 7: CLASSES AND OBJECTS

There are no bounds to the types of questions you can be asked about classes and objects. Some interviewers are syntax-fixated and might throw some complicated code at you. Others are less concerned with the implementation and more interested in your design skills.

Things to Remember

  • Basic class definition syntax
  • Access specifiers for methods and data members
  • The use of the this pointer
  • How name resolution works, which resolves a name first by local scope, then class scope (implying this->) and then global scope
  • Object creation and destruction, both on the stack and the heap
  • Cases when the compiler generates a constructor for you
  • Constructor initializers
  • Copy constructor and assignment operator
  • The mutable keyword
  • Method overloading and default parameters
  • Friend classes and methods
  • Managing dynamically allocated memory in objects
  • static methods and members
  • Inline methods and the fact that the inline keyword is just a hint for the compiler which can ignore the hint
  • The key idea of separating interface and implementation classes, which says that interfaces should only contain public methods, and should be as stable as possible; they should not contain any data members or private/protected methods; thus, interfaces can remain stable while implementations are free to change under them.
  • C++11 initializer lists
  • C++11 in-class member initializers
  • C++11 explicitly defaulted and deleted special member functions

Types of Questions

Questions such as, “What does the keyword mutable mean?” make great phone screening questions. A recruiter may have a list of C++ terms and will move candidates to the next stage of the process based on the number that they get right. You may not know all of the terms that are thrown at you, but keep in mind that other candidates are facing the same questions and it’s one of the few metrics available to a recruiter.

The find-the-bug style of questions is popular among interviewers and course instructors alike. You will be presented with some nonsense code and asked to point out its flaws. Interviewers struggle to find quantitative ways to analyze candidates, and this is one of the few ways to do it. In general, your approach should be to read each line of code and voice your concerns, brainstorming aloud. The types of bugs can fall into these categories:

  • Syntax errors: These are rare — interviewers know you can find compile-time bugs with a compiler.
  • Memory problems: These include problems such as leaks and double deletion.
  • “You wouldn’t do that” problems: This category includes things that are technically correct but are not recommended. For example, don’t use C-style character arrays, use std::string instead.
  • Style errors: Even if the interviewer doesn’t count it as a bug, point out poor comments or variable names.

Here’s a find-the-bug problem that demonstrates each of these areas:

class Buggy
{
        Buggy(int param);
        ~Buggy();
        double fjord(double inVal);
        int fjord(double inVal);
    protected:
        void turtle(int i = 7, int j);
        int param;
        double* mGraphicDimension;
};
Buggy::Buggy(int param)
{
    param = param;
    mGraphicDimension = new double;
}
Buggy::~Buggy()
{
}
double Buggy::fjord(double inVal)
{
    return inVal * param;
}
int Buggy::fjord(double inVal)
{
    return (int)fjord(inVal);
}
void Buggy::turtle(int i, int j)
{
    cout << "i is " << i << ", j is " << j << endl;
}

Take a careful look at the code, and then consult the following corrected version for the answers:

#include <iostream>          // Streams are used in the implementation.
class Buggy
{
    public:                  // These should most likely be public.
        Buggy(int inParam);  // Parameter naming.
        virtual ~Buggy();    // Recommended to make destructors virtual.
        Buggy(const Buggy& src);            // Provide copy ctor and operator=
        Buggy& operator=(const Buggy& rhs); // when the class has dynamically 
                                            // allocated memory.
        Buggy(Buggy&& src);            // C++11: provide move ctor and operator=
        Buggy& operator=(Buggy&& rhs); // when the class has dynamically 
                                       // allocated memory to increase
                                       // performance. (See Chapter 9).
        double fjord(double inVal); // int version won't compile. Overloaded
                                    // methods cannot differ only in return type.
    protected:
        void turtle(int i, int j);  // Only last arguments can have defaults.
        int mParam;                 // Data member naming
        double* mGraphicDimension;
};
Buggy::Buggy(int inParam) : mParam(inParam)
{
    mGraphicDimension = new double;
}
Buggy::~Buggy()
{
    delete mGraphicDimension;  // Avoid memory leak.
    mGraphicDimension = nullptr;
}
Buggy::Buggy(const Buggy& src)
{
    mParam = src.mParam;
    mGraphicDimension = new double;
    *mGraphicDimension = *(src.mGraphicDimension);
}
Buggy& Buggy::operator=(const Buggy& rhs)
{
    if (this == &rhs) {
        return *this;
    }
    mParam = rhs.mParam;
    delete mGraphicDimension;
    mGraphicDimension = new double;
    *mGraphicDimension = *(rhs.mGraphicDimension);
    return *this;
}
Buggy::Buggy(Buggy&& src)
{
    mParam = src.mParam;
    mGraphicDimension = src.mGraphicDimension;
    src.mGraphicDimension = nullptr;
}
Buggy& Buggy::operator=(Buggy&& rhs)
{
    if (this == &rhs) {
        return *this;
    }
    mParam = rhs.mParam;
    mGraphicDimension = rhs.mGraphicDimension;
    rhs.mGraphicDimension = nullptr;
    return *this;
}
double Buggy::fjord(double inVal)
{
    return inVal * mParam;    // Changed data member name
}
void Buggy::turtle(int i, int j)
{
    std::cout << "i is " << i << ", j is " << j << std::endl; // Namespaces
}

For this example, you should also mention that it’s recommended to use a smart pointer, such as the C++11 shared_ptr, instead of the dumb mGraphicDimension pointer, and include an explanation of why a smart pointer is recommended.

CHAPTER 8: DISCOVERING INHERITANCE TECHNIQUES

Questions about inheritance usually come in the same forms as questions about classes. The interviewer might also ask you to implement a class hierarchy to show that you have worked with C++ enough to subclass without looking it up in a book.

Things to Remember

  • The syntax for subclassing a class
  • The difference between private and protected from a subclass point of view
  • Method overriding and virtual
  • The reason why destructors should be virtual
  • Chained constructors
  • The ins and outs of upcasting and downcasting
  • The principle of polymorphism
  • Pure virtual methods and abstract base classes
  • Multiple inheritance
  • Run Time Type Information (RTTI)
  • C++11 inherited constructors
  • The C++11 final keyword on classes
  • The C++11 override and final keywords on methods

Types of Questions

Many of the pitfalls in inheritance questions are related to getting the details right. When you are writing a base class, don’t forget to make the methods virtual. If you mark all methods virtual, be prepared to justify that decision. You should be able to explain what virtual means and how it works. Also, don’t forget the public keyword before the name of the parent class in the subclass definition (e.g., class Sub : public Super). It’s unlikely that you’ll be asked to perform nonpublic inheritance during an interview.

More challenging inheritance questions have to do with the relationship between a superclass and a subclass. Be sure you know how the different access levels work, and the difference between private and protected. Remind yourself of the phenomenon known as slicing, when certain types of casts cause a class to lose its subclass information.

CHAPTER 9: UNDERSTANDING C++ QUIRKS AND ODDITIES

Many interviewers tend to focus on the more obscure cases because that way experienced C++ programmers can demonstrate that they have conquered the unusual parts of C++. Sometimes interviewers have difficulty coming up with interesting questions and end up asking the most obscure question they can think of.

Things to Remember

  • References must be bound to a variable when they are declared and the binding cannot be changed.
  • The advantages of pass-by-reference over pass-by-value
  • The many uses of const
  • The many uses of static
  • The different types of casts in C++
  • The difference between rvalues and lvalues
  • How typedefs work
  • C++11 rvalue references
  • C++11 move semantics with move constructors and move assignment operators
  • C++11 type aliasing using the template alias feature
  • C++11 uniform initialization
  • C++11 alternative function syntax
  • C++11 nullptr

Types of Questions

Asking a candidate to define const and static is a classic C++ interview question. Both keywords provide a sliding scale with which an interviewer can assess an answer. For example, a fair candidate will talk about static methods and static data members. A good candidate will give good examples of static methods and static data members. A great candidate will also know about static linkage and static variables in functions.

The edge cases described in this chapter also come in find-the-bug type problems. Be on the lookout for misuse of references. For example, imagine a class that contains a reference as a data member:

class Gwenyth
{
    public:
        int& mCaversham;
};

Because mCaversham is a reference, it needs to be bound to a variable when the class is constructed. To do that, you’ll need to use a constructor initializer. The class could take the variable to be referenced as a parameter to the constructor:

class Gwenyth
{
    public:
        Gwenyth(int& i);
        int& mCaversham;
};
Gwenyth::Gwenyth(int& i) : mCaversham(i)
{
}

CHAPTER 10: HANDLING ERRORS

Managers sometimes shy away from hiring recent graduates or novice programmers for vital (and high-paying) jobs because it is assumed that they don’t write production-quality code. You can prove to an interviewer that your code won’t keel over randomly by demonstrating your error-handling skills during an interview.

Things to Remember

  • Syntax of exceptions
  • Catch exceptions as const references.
  • For production code, hierarchies of exceptions are preferable to a few generic ones.
  • Throw lists in C++ are not like throw lists in Java.
  • Smart pointers help avoid memory leaks when exceptions are thrown.
  • The basics of how stack unwinding works when an exception gets thrown
  • How to handle errors in constructors and destructors
  • Why you should never use the C functions setjmp() and longjmp() in C++

Types of Questions

Interviewers will be on the lookout to see how you report and handle errors. When you are asked to write a piece of code, make sure you implement proper error handling.

You might be asked to give a high-level overview of how stack unwinding works when an exception is thrown, without implementation details.

Of course, not all programmers understand or appreciate exceptions. Some may even have a completely unfounded bias against them for performance reasons. If the interviewer asks you to do something without exceptions, you’ll have to revert to traditional nullptr checks and error codes. That would be a good time to demonstrate your knowledge of nothrow new.

An interviewer can also ask questions in the form of “Would you use this?” One example question could be “Would you use setjmp()/longjmp() in C++, since they are more efficient than exceptions?” Your answer should be a big no, because setjmp()/longjmp() cannot possibly work in C++ because they bypass scoped destructors, and the fact that exceptions have a big performance penalty is a misconception. On modern compilers, exceptions have close to zero cost.

CHAPTERS 11, 12, 13 AND 17: THE STANDARD TEMPLATE LIBRARY

As you’ve seen, certain aspects of the STL can be difficult to work with. Few interviewers would expect you to recite the details of STL classes unless you claim to be an STL expert. If you know that the job you’re interviewing for makes heavy use of the STL, you might want to write some STL code the day before to refresh your memory. Otherwise, recalling the high-level design of the STL and its basic usage should suffice.

Things to Remember

  • The different types of containers and their relationships with iterators
  • Basic usage of vector, which is probably the most frequently used STL class
  • Usage of associative containers, such as map
  • Usage of C++11 unordered associative containers, such as unordered_map, and the differences with associative containers
  • The purpose of STL algorithms and some of the built-in algorithms
  • The ways in which you can extend the STL (details are most likely unnecessary)
  • Usage of C++11 lambda expressions in combination with STL algorithms
  • The remove-erase-idiom
  • Your own opinions about the STL

Types of Questions

If interviewers are dead set on asking detailed STL questions, there really are no bounds to the types of questions they could ask. If you’re feeling uncertain about syntax though, you should state the obvious during the interview — “In real life, of course, I’d look that up in Professional C++, but I’m pretty sure it works like this . . .” At least that way the interviewer is reminded that he or she should forgive the details as long as you get the basic idea right.

High-level questions about the STL are often used to gauge how much you’ve used the STL without making you recall all the details. For example, casual users of the STL are familiar with associative and non-associative containers. A slightly more advanced user would be able to define an iterator and describe how iterators work with containers. An even more advanced user should be familiar with the remove-erase-idiom and should be able to explain in which cases you can use it and what its benefits are. An interviewer might also gauge your knowledge about lambda expressions which are new in C++11. Other high-level questions could ask you about your experience with STL algorithms or whether you’ve customized the STL.

CHAPTER 14: USING STRINGS AND REGULAR EXPRESSIONS

Strings are very important, in every kind of application. An interviewer will most likely ask at least one question related to string handling in C++.

Things to Remember

  • The std::string class
  • Differences between the C++ std::string class and C-style strings, including why C-style strings should be avoided
  • Conversion of strings to numeric types like integers and floating point numbers, and vice versa
  • C++11 raw string literals
  • The importance of localization
  • Ideas behind Unicode
  • The concepts of locales and facets
  • What regular expressions are

Types of Questions

An interviewer could ask you to explain how you can append two strings together. With this question he or she wants to find out whether you are thinking as a professional C++ programmer or as a C programmer. If you get such a question, you should explain the std::string class, and show how to use it to append two strings. It’s also worth mentioning that the string class will handle all memory management for you automatically and contrast this to C-style strings.

Your interviewer may not ask specifically about localization, but you can show your worldwide interest by using wchar_t instead of char during the interview. If you do receive a question about your experience with localization, be sure to mention the importance of considering worldwide use from the beginning of the project.

You may also be asked about the general idea behind locales and facets. You probably will not have to explain the exact syntax, but you should explain that they allow you to format text and numbers according to the rules of a certain language/country.

You might get a question about Unicode, but most likely it will be a question to explain the ideas and the basic concepts behind Unicode instead of implementation details. So, make sure you understand the high-level concepts of Unicode and that you can explain their use in the context of localization. You should also know about the different options for encoding Unicode characters, such as UTF-8 and UTF-16, without specific details.

As seen in this chapter, regular expressions can have a daunting syntax. It is unlikely that an interviewer will ask you about little details of regular expressions. However, you should be able to explain the concept of regular expressions and what kind of string manipulations you can do with them.

CHAPTER 15: DEMYSTIFYING C++ I/O

If you’re interviewing for a job writing GUI applications, you probably won’t get too many questions about I/O streams because GUI applications tend to use other mechanisms for I/O. However, streams can come up in other problems and, as a standard part of C++, they are fair game as far as the interviewer is concerned.

Things to Remember

  • The definition of a stream
  • Basic input and output using streams
  • The concept of manipulators
  • Types of streams (console, file, string, etc.)
  • Error-handling techniques

Types of Questions

I/O may come up in the context of any question. For example, the interviewer could ask you to read in a file containing test scores and put them in a vector. This question tests basic C++ skills, basic STL, and basic I/O. Even if I/O is only a small part of the problem you’re working on, be sure to check for errors. If you don’t, you’re giving the interviewer an opportunity to say something negative about your otherwise perfect program.

CHAPTER 16: ADDITIONAL LIBRARY UTILITIES

Chapter 16 describes a number of new features and libraries in the C++11 standard. An interviewer might touch on a few of those topics to see whether you are keeping up-to-date with the latest developments in the C++ world.

Things to Remember

  • The use of std::function
  • The Chrono library to work with durations, clocks, and time points
  • The C++11 method of generating random numbers
  • std::tuple as a generalization of std::pair

Types of Questions

You don’t need to expect detailed questions about these topics. A possible question could be to explain the usage of std::function. You might also get a question to explain the basic ideas and concepts of the new Chrono and random number generation libraries, but without going into syntax details. If the interviewer starts focusing on random numbers, it is important to explain the differences between true random numbers and pseudo random numbers.

CHAPTER 18: OVERLOADING C++ OPERATORS

It’s possible, though somewhat unlikely, that you would have to perform something more difficult than a simple operator overload during an interview. Some interviewers like to have an advanced question on hand that they don’t really expect anybody to answer correctly. The intricacies of operator overloading make great nearly-impossible questions because few programmers get the syntax right without looking it up. That means it’s a great area to review before an interview.

Things to Remember

  • Overloading stream operators, because they are the most commonly overloaded operators, and are conceptually unique
  • What a functor is and how to create one
  • Choosing between a method operator or a global friend function
  • Some operators can be expressed in terms of others, i.e., operator<= can be written by complementing the result of operator>.
  • The use of C++11 rvalue references to implement move assignment operators

Types of Questions

Let’s face it — operator overloading questions (other than the simple ones) are cruel. Anybody who is asking such questions knows this and is going to be impressed when you get it right. It’s impossible to predict the exact question that you’ll get, but the number of operators is finite. As long as you’ve seen an example of overloading each operator that makes sense to overload, you’ll do fine!

Besides asking you to implement an overloaded operator, you could be asked high-level questions about overloaded operators. A find-the-bug question could contain an operator that is overloaded to do something that is conceptually wrong for that particular operator. In addition to syntax, keep the use cases and theory of operator overloading in mind.

CHAPTERS 19 AND 20: TEMPLATES

As one of the most arcane parts of C++, templates are a good way for interviewers to separate the C++ novices from the pros. While most interviewers will forgive you for not remembering some of the advanced template syntax, you should go into the interview knowing the basics.

Things to Remember

  • How to write a basic templatized class
  • How to use a templatized class
  • The C++11 alternative function syntax and its use for calculating the type of the return value (type inference)
  • C++11 template aliases and why they are better than typedefs
  • The concept of C++11 variadic templates
  • The ideas behind metaprogramming

Types of Questions

Many interview questions start out with a simple problem and gradually add complexity. Often, interviewers have an endless amount of complexity that they are prepared to add, and they simply want to see how far you get. For example, an interviewer might begin a problem by asking you to create a class that provides sequential access to a fixed number of ints. Next, the class will need to grow to accommodate an arbitrary sized array. Then, it will need arbitrary data types, which is where templates come in. From there, the interviewer could take the problem in a number of directions, asking you to use operator overloading to provide array-like syntax, or continuing down the template path by asking you to provide a default type.

Templates are more likely to be employed in the solution of another coding problem than to be asked about explicitly. You should brush up on the basics in case the subject comes up. However, most interviewers understand that the template syntax is difficult, and asking someone to write complex template code in an interview is rather cruel.

The interviewer might ask you high-level questions related to metaprogramming to find out whether you have heard about it or not. While explaining, you could give a small example such as compile-time loop unrolling. Don’t worry if the syntax for your example is not entirely correct. As long as you explain what it is supposed to do, you should be fine.

CHAPTER 21: EFFECTIVE MEMORY MANAGEMENT

You can be sure that an interviewer will ask you some questions related to memory management, including your knowledge of smart pointers. Besides smart pointers, you will also get more low-level questions. The goal is to determine whether the object-oriented aspects of C++ have distanced you too much from the underlying implementation details. Memory management questions will give you a chance to prove that you know what’s really going on.

Things to Remember

  • Drawing the stack and the heap can help you understand what’s going on.
  • Use new and delete instead of malloc() and free().
  • Use new[] and delete[] for arrays.
  • If you have an array of pointers to objects, you still need to allocate memory for each individual pointer and delete the memory — the array allocation syntax doesn’t take care of pointers.
  • The existence of memory allocation problem detectors, such as Valgrind, to expose memory problems
  • Smart pointers and specifically the new C++11 std::shared_ptr and std::unique_ptr, and why you should not use the old std::auto_ptr
  • Use std::make_shared() to create a std::shared_ptr.

Types of Questions

Find-the-bug questions often contain memory issues, such as double-deletion, new/new[] mix-up, and memory leaks. When you are tracing through code that makes heavy use of pointers and arrays, you should draw and update the state of memory as you process each line of code. Even if you see the answer right away, it will let the interviewer know that you’re able to draw the state of memory.

Another good way to find out if a candidate understands memory is to ask how pointers and arrays differ. At this point, the differences may be so tacit in your mind that the question catches you off-guard for a moment. If that’s the case, skim Chapter 21 again for the discussion.

When answering questions about memory allocation, it’s always a good idea to mention the concept of smart pointers and their benefits for automatically cleaning up memory or other resources. You definitely should also mention that it’s much better to use STL containers like std::vector instead of C-style arrays because the STL containers handle memory management for you automatically.

CHAPTER 22: MULTITHREADED PROGRAMMING WITH C++

Multithreaded programming is becoming more and more important with the release of multicore processors for everything from servers to consumer computers. Even the latest smartphones have multicore processors. An interviewer might ask you a couple of multithreading questions. C++11 includes a standard threading library, so it’s a good idea to know how it works.

Things to Remember

  • Race conditions and deadlocks and how to prevent them
  • The atomic types and atomic operations for possible lock-free programming
  • std::thread to spawn threads
  • The concept of mutual exclusion, including the usage of the different mutex and lock classes, to provide synchronization between threads
  • Condition variables and how to use them to signal other threads
  • What futures and promises are
  • Copying and rethrowing of exceptions across thread boundaries

Types of Questions

Since the multithreading library is only available since C++11, you don’t need to expect detailed questions, unless you are interviewing for a specific multithreading programming position.

An interviewer might ask you high-level questions, such as asking you to explain the general concepts behind multithreaded programming. This is a very broad question but allows the interviewer to get an idea of your multithreaded knowledge.

CHAPTER 23: MAXIMIZING SOFTWARE ENGINEERING METHODS

You should be suspicious if you go through the complete interview process with a company, and the interviewers do not ask any process questions — it may mean that they don’t have any process or that they don’t care about it. Alternatively, they might not want to scare you away with their process behemoth.

Source code control is also an important aspect of any development process.

Most of the time, you’ll get a chance to ask questions regarding the company. We suggest you consider asking about engineering processes and source code control solutions as one of your standard questions.

Things to Remember

  • Traditional life-cycle models
  • The tradeoffs of formal models, such as the Rational Unified Process
  • The main principles of Extreme Programming
  • Scrum as an example of an agile process
  • Other processes you have used in the past
  • Principles behind source code control solutions

Types of Questions

The most common question you’ll be asked is to describe the process that your previous employer used. When answering, you should mention what worked well and what failed, but try not to denounce any particular methodology. The methodology you criticize could be the one that your interviewer uses.

The authors spend a dizzying amount of their time reading resumes and one trend is clear — everybody is listing Extreme Programming as a skill these days. While there’s little hard data on the subject, it certainly seems unlikely that strict adherence to XP is commonplace in programming environments. What we’ve found is that many organizations have started to look into XP and have adopted some of its principles without subscribing to it in any formal way.

If the interviewer asks you about XP, he or she probably doesn’t want you to simply recite the textbook definition — the interviewer knows that you can read the table of contents of an XP book. Instead, pick a few ideas from XP that you find appealing. Explain each to the interviewer along with your thoughts on them. Try to engage the interviewer in a conversation, proceeding in a direction in which he or she is interested based on the cues that person gives.

If you get a question regarding source code control it will most likely be a high-level question. You should explain the general principles behind source code control solutions, mention the fact that there are commercial and free open-source solutions available, and explain how source code control happened at your previous employer.

CHAPTER 24: WRITING EFFICIENT C++

Efficiency questions are quite common in interviews because many organizations are facing scalability issues with their code and need programmers who are savvy about performance.

Things to Remember

  • Language level efficiency is important, but it can only go so far; design-level choices are ultimately more significant.
  • Reference parameters are more efficient because they avoid copying.
  • Object pools can help avoid the overhead of creating and destroying objects.
  • Profiling is vital to determine which operations are really consuming the most running time.

Types of Questions

Often, the interviewer will use their own product as an example to drive efficiency questions. Sometimes the interviewer will describe an older design and some performance-related symptoms they experienced. The candidate is supposed to come up with a new design that alleviates the problem. Unfortunately, there is a major problem with a question like this — what are the odds that you’re going to come up with the same solution that the company did when the problem was actually solved? Because the odds are slim, you need to be extra careful to justify your designs. You may not come up with the actual solution, but you can still have an answer that is correct or even better than the company’s newer design.

Other types of efficiency questions may ask you to tweak some C++ code for performance or iterate on an algorithm. For example, the interviewer could show you code that contains extraneous copies or inefficient loops.

The interviewer might also ask you for a high-level description of profiling tools and what their benefits are.

CHAPTER 25: DEVELOPING CROSS-PLATFORM AND CROSS-LANGUAGE APPLICATIONS

Few programmers submit resumes that list only a single language or technology, and few large applications rely on only a single language or technology. Even if you’re interviewing for only a C++ position, the interviewer can still ask questions about other languages, especially as they relate to C++.

Things to Remember

  • The ways in which platforms can differ (architecture, sizes, etc.)
  • The fine line between programming and scripting
  • The interactions between C++ and other languages

Types of Questions

The most popular cross-language question is to compare and contrast two different languages. You should avoid saying just positive or just negative things about a particular language, even if you really love or hate that other language. The interviewer wants to know that you are able to see tradeoffs and make decisions based on them.

Cross-platform questions are more likely to be asked while discussing previous work. If your resume indicates that you once wrote C++ applications that ran on a custom hardware platform, you should be prepared to talk about the compiler you used and the challenges of that platform.

CHAPTER 26: BECOMING ADEPT AT TESTING

Potential employers value strong testing abilities. Because your resume probably doesn’t indicate your testing skills, unless you have explicit QA experience, you might face interview questions about testing.

Things to Remember

  • The difference between black box and white box testing
  • The concept of unit testing, integration testing, system testing, regression testing and writing tests along with code
  • Techniques for higher-level tests
  • Testing and QA environments in which you’ve worked before: What worked and what didn’t?

Types of Questions

An interviewer could ask you to write some tests during the interview, but it’s unlikely that a program presented during an interview would contain the depth necessary for interesting tests. It’s more likely that you will be asked high-level testing questions. Be prepared to describe how testing was done at your last job, and what you liked and didn’t like about it. After you answer, this is a good question for you to ask the interviewer. It might start a conversation about testing and give you a better idea of the environment at your potential job.

CHAPTER 27: CONQUERING DEBUGGING

Engineering organizations look for candidates who are able to debug both their own code as well as code that they’ve never seen before. Technical interviews often attempt to size up your debugging muscles.

Things to Remember

  • Debugging doesn’t start when bugs appear; you should instrument your code ahead of time, so you’re prepared for the bugs when they arrive.
  • Logs and debuggers are your best tools.
  • Asserts and the reason why you should avoid the standard assert() macro from <cassert>
  • How to use the C++11 static asserts
  • The symptoms that a bug exhibits may appear to be unrelated to the actual cause.
  • Object diagrams can be helpful in debugging, especially during an interview.

Types of Questions

During an interview, you might be challenged with an obscure debugging problem. Remember that the process is the most important thing, and the interviewer probably knows that. Even if you don’t find the bug during the interview, make sure that the interviewer knows what steps you would go through to track it down. If the interviewer hands you a function and tells you that it crashes during execution, he or she should award just as many points to a candidate who properly discusses the sequence of steps to find the bug, as to a candidate who finds it right away.

CHAPTER 28: INCORPORATING DESIGN TECHNIQUES AND FRAMEWORKS

Each of the techniques presented in Chapter 28 makes a fine interview question. Rather than repeat what you already read in the chapter, we suggest that you skim back over Chapter 28 prior to an interview to make sure that you are able to understand each of the techniques.

If you are being interviewed for a GUI-based job, you should know about the existence of frameworks such as MFC, Qt, and possibly others.

CHAPTER 29: APPLYING DESIGN PATTERNS

Because design patterns are very popular in the professional world (many candidates even list them as skills), it’s likely that you’ll encounter an interviewer who wants you to explain a pattern, give a use case for a pattern, or implement a pattern.

Things to Remember

  • The basic idea of a pattern as a reusable object-oriented design concept
  • The patterns you have read about in this book, as well as others that you’ve used in your work
  • There are hundreds of patterns with often-conflicting names, so you and your interviewer may use different words for the same pattern.

Types of Questions

Answering questions about design patterns is usually a walk in the park, unless the interviewer expects you to know the details of every single pattern known to humankind. Luckily, most interviewers who appreciate design patterns will just want to chat with you about them and get your opinions. After all, looking up concepts in a book or online instead of memorizing them is a good pattern itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset