C++ Interviews - Professional C++ (2014)

Professional C++ (2014)

Appendix AC++ 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 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++ AND THE STL

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

· 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, including the range-based for loop, the conditional operator, and variables

· The difference between the stack and the heap

· Dynamically allocated arrays

· Use of const

· What references are

· The auto keyword

· Basic use of STL containers such as std::vector

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.

CHAPTERS 2 AND 18: STRINGS, LOCALIZATION, AND REGULAR EXPRESSIONS

Strings are very important, and are used in almost 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 such as integers and floating point numbers, and vice versa

· 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 thestd::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 Chapter 18, 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 3: 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 meta information

· The principle of decomposition

· The principle of refactoring

· Naming techniques

Types of Questions

Style questions can come in a few different forms. A friend of mine 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. 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 confidential, 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 also communicate to others how to effectively use that code. Of course, having a book title attached to your name is also a big plus.

CHAPTER 4: 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 platform independent C++ libraries;www.sourceforge.net for libraries for different platforms; and so on. Giving examples of some of the licenses that are available for open-source software, such as the GPL license, Boost license, Creative Commons license, CodeGuru license, OpenBSD license, and so on, might score you extra credit.

CHAPTER 5: 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 those 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, it’s recommended 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 6: 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.

CHAPTERS 7 AND 8: 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

· Delegating constructors

· The mutable keyword

· Method overloading and default parameters

· Friend classes and methods

· Managing dynamically allocated memory in objects

· static methods and data 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.

· Initializer lists

· In-class member initializers

· 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 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) noexcept; // Provide move ctor and operator=

Buggy& operator=(Buggy&& rhs) noexcept; // when the class has dynamically

// allocated memory to increase

// performance. (See Chapter 10).

double fjord(double inVal); // int version won't compile. Overloaded

// methods cannot differ only in return type.

private: // Use private by default.

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) // Prefer using the ctor initializer

{

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) noexcept

{

mParam = src.mParam;

mGraphicDimension = src.mGraphicDimension;

src.mGraphicDimension = nullptr;

}

Buggy& Buggy::operator=(Buggy&& rhs) noexcept

{

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 must also mention that it’s better to avoid dynamic memory, or, if you can’t avoid it, to use a smart pointer, such as a unique_ptr, instead of the dumb mGraphicDimension pointer. Include an explanation of why a smart pointer is required, and explain the impact on the implementation of the Buggy class.

CHAPTER 9: 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 write derived classes without looking it up in a book.

Things to Remember

· The syntax for deriving a class

· The difference between private and protected from a derived class point of view

· Method overriding and virtual

· What the difference is between overloading and overriding

· 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)

· Inherited constructors

· The final keyword on classes

· The 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 whatvirtual means and how it works. Also, don’t forget the public keyword before the name of the parent class in the derived class definition (e.g., class Derived : public Base). 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 base class and a derived class. Be sure you know how the different access levels work, and the difference between private and protected. Remind yourself of the phenomenon known asslicing, when certain types of casts cause a class to lose its derived class information.

CHAPTER 10: C++ QUIRKS, ODDITIES, AND INCIDENTALS

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++

· How typedefs and type aliases work

· The difference between rvalues and lvalues

· Rvalue references

· Move semantics with move constructors and move assignment operators

· Uniform initialization

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

{

private:

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);

private:

int& mCaversham;

};

Gwenyth::Gwenyth(int& i) : mCaversham(i)

{

}

CHAPTERS 11 AND 21: 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 use a class template

· How to write a basic class template

· The alternative function syntax and its use for deducing the type of the return value (type inference)

· Alias templates and why they are better than typedefs

· The concept of 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 calculating the factorial of a number at compile time. Don’t worry if the syntax is not entirely correct. As long as you explain what it is supposed to do, you should be fine.

CHAPTER 12: 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 13: 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

· The basics of how stack unwinding works when an exception gets thrown

· How to handle errors in constructors and destructors

· Smart pointers help avoid memory leaks when exceptions are thrown

· 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 nullptrchecks 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. The fact that exceptions have a big performance penalty is a misconception. On modern compilers, having code that can handle potential exceptions has close to zero performance penalty.

CHAPTER 14: 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 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 rvalue references to implement move assignment operators

Types of Questions

Let’s face it — operator overloading questions (other than the simple ones) can be 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 operator overloading. 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 15, 16, 17, AND 20: 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 use of vector, which is probably the most frequently used STL class

· Use of associative containers, such as map

· The differences between associative containers and unordered associative containers, such as unordered_map

· The purpose of STL algorithms and some of the built-in algorithms

· The use of lambda expressions in combination with STL algorithms

· The ways in which you can extend the STL (details are most likely unnecessary)

· 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, describe how iterators work with containers, and describe the remove-erase-idiom. Other high-level questions could ask you about your experience with STL algorithms or whether you’ve customized the STL. An interviewer might also gauge your knowledge about lambda expressions, and their use with STL algorithms.

CHAPTER 19: ADDITIONAL LIBRARY UTILITIES

This chapter describes a number of smaller features and additional libraries from the C++ standard, including some C++11 and C++14 features. 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

· Use the <random> library as the preferred method of generating random numbers.

· Standard user-defined literals

· 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 use of std::function. You might also get a question to explain the basic ideas and concepts of the 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 22: 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 std::shared_ptr and std::unique_ptr, and that you should not use the old deprecated std::auto_ptr

· Use std::make_unique() to create a std::unique_ptr

· Use std::make_shared() to create a std::shared_ptr

Tpyes of Questions

Find-the-bug questions often contain memory issues, such as double deletion, new/delete/new[]/delete[] 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.

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 22 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 23: 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 smartphones have multicore processors. An interviewer might ask you a couple of multithreading questions. C++ 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

· std::thread to spawn threads

· The atomic types and atomic operations

· The concept of mutual exclusion, including the use of the different mutex and lock classes, to provide synchronization between threads

· Condition variables and how to use them to signal other threads

· Futures and promises

· Copying and rethrowing of exceptions across thread boundaries

Types of Questions

Multithreading programming is a complicated subject, so you don’t need to expect detailed questions, unless you are interviewing for a specific multithreading programming position.

Instead, an interviewer might ask you to explain the different kinds of problems you can encounter with multithreaded code; Problems such as race conditions, deadlocks, tearing, and cache coherency. You can also be asked to explain the general concepts behind multithreaded programming. This is a very broad question but allows the interviewer to get an idea of your multithreading knowledge.

CHAPTER 24: 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. Another important aspect of any development process is source code control.

Most of the time, you’ll get a chance to ask questions regarding the company. I 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.

Almost every candidate 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. It is more likely 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 possibly explain how source code control happened at your previous employer.

CHAPTER 25: 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 much more significant.

· Avoid algorithms with bad complexity, such as quadratic algorithms.

· 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 time, so you don’t waste effort trying to optimize code that is not a performance bottleneck.

Types of Questions

Often, the interviewer will use his or her own product as an example to drive efficiency questions. Sometimes the interviewer will describe an older design and some performance-related symptoms he or she 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 26: 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 bugs when they arrive

· Logs and debuggers are your best tools

· How to use assertions

· How to use static assertions

· 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.