share
Stack OverflowFavorite C++ interview question
[+54] [20] Omega
[2008-09-08 19:11:25]
[ c++ interview-questions ]
[ http://stackoverflow.com/questions/50447] [DELETED]

What is your favorite C++ interview question? It may be any question, for example:

algorithms, multithreding, gamedev area, low-level system programming, strings...

[+34] [2008-09-08 19:14:24] Gulzar Nazim

FizzBuzz [1] :)

I love these phone-screen questions from Steve Yegge [2].

[1] http://www.codinghorror.com/blog/archives/000781.html
[2] http://steve.yegge.googlepages.com/five-essential-phone-screen-questions

(1) These are also obviously phoney screen questions in some sence ;) - mlvljr
1
[+32] [2008-09-16 11:24:52] 0124816

I usually try to avoid asking candidates language specific questions: intelligence and adaptability are more important to me. I think any smart person should be able to learn C++ fairly quickly, and I don't think knowing language specific trivia (e.g. how to write a custom allocator for a stl type) is a good indication of a candidates potential.


(5) Depends on your definition of "learn". A smart person can acquire basic proficiency in C++ fairly quickly, but C++ is a complicated beast and mastering it takes allot of reading and experience. Questions should be level appropriate, i.e. if you just need someone with basic proficiency ask basic questions, if you need a library architect ask advanced questions, etc... - Robert S. Barnes
Sure, but I'm sometimes not looking for someone that I have to train up in the language we use. I want a C++ developer, which involves candidates knowing C++. - Lightness Races in Orbit
I agree, I would upvote 10X if I could. Tying a person to specific syntax or (god forbid) set of libraries is a sin! - Mihaela
2
[+25] [2009-09-25 14:09:39] Mark Bessey

When phone-screening candidates, I sometimes ask:

When does a class need a virtual destructor?

This should be an extremely easy question for someone who has done any amount of C++ class design, but is really hard for people who list C++ on their resume, but don't have any actual experience with it.


3
[+21] [2008-09-16 11:29:32] Michael Pliskin

If speaking of a just one, what is a smart pointer? With a detailed description and typical usage guidelines. Simple and reveals C++ background quickly.


I ask this, with the addition of asking about intrusive/non-intrusive refcounting implementations. - Lightness Races in Orbit
4
[+19] [2008-09-08 19:22:16] Daren Thomas

I was asked this one in a c++ course final exam:

Say you have a class Parent with a virtual method a and a class Child that implements a. You also have a bunch of functions:

void f1(Parent p) { p.a(); }
void f2(Parent* p) { p->a(); }
void f3(Parent& p) { p.a(); }

When called with a Child instance, which method will be invoked for f1, f2 and f3?


The answer can be found out by thinking through what happens when f1 is passed a child object. What can the compiler know? How is the object passed? (hint: copy constructor). - Daren Thomas
(10) Parent::a, child::a, child::a. It's an example of the C++ slicing problem - StackedCrooked
Is this because in first case whole Parent object is copied into stack, but in two last methods only a reference or a pointer is copied into a stack? - Sergej Andrejev
5
[+14] [2009-09-25 12:52:41] Mahin

Not specifically C++, but it was about Pointers.

Can a pointer point to itself ?

Answer to this question has earned me my first job.


(4) Yes, it can, but only if it's a void*. I guess the interesting part here us the discussion of why it's not possible to declare a type that can point to itself. I suppose you could also talk about what kinds of errors might lead to a pointer that appears to point to itself. - Mark Bessey
(9) Does this count: struct selfptr { struct selfptr *ptr; } ? The struct and its ptr member would have the same address, and you could follow it as many times as you like: obj->ptr->ptr->ptr ... - Nefrubyr
(1) @Mahin: What did you answer? - Lazer
(3) @eSKay : I answered politically. I answered .. Theoritically I can say it should but practically I have never done this. In reply interviewer has asked me to try and offered his help with it. I answered it correctly but with his help. - Mahin
(1) @ Tomalak Geret'kal : Dont you think you need double pointer there... :) - Mahin
(1) void* ptr = NULL; ptr = &ptr; - Evan Moran
Follow-up question to this answer - Can a pointer ever point to itself? - Lazer
6
[+12] [2008-09-08 19:20:26] kender

This article: The Guerrilla Guide to Interviewing [1] has some quite nice thoughts about interviewing and asking C-questions. Personally, I don't see algorithms as a pure C/C++ question.

Multithreading - questions about threads are evil, really many programmers won't be able to anwser them correctly (they seem to be quite like Joel's pointers questions).

Gamedev - if it's your industry, ask them, but it's not some kind of skill a programmer should have when applying for a job.

And questions about strings are really about pointers, so reaction of the person you're talking to as soon as he hear that question should tell you much about him/her.

My personal favorite question is always related to a project someone worked on. Listen carefully what he's talking about and try to figure and ask what he could have done better. If it will be about pointers, ask. Really, many people feel much better when they talk about their recent work then when they have to anwser some theoretical questions.

[1] http://www.joelonsoftware.com/articles/fog0000000073.html

7
[+10] [2010-02-09 11:52:38] Kristopher Johnson

An old boss of mine used to ask candidates to write a function to swap the two bytes of a 16-bit value. 75% of the candidates had no idea how to do it.

If a candidate couldn't do it, the follow-up question was "What is 13 in hexadecimal?" Most of the candidates who couldn't do that first exercise also had no idea how to answer this. (The boss told one candidate that she should give her Ph.D. back to her university.)

These very-simple questions got rid of lots of candidates. It made me sad.


(2) Ph.D? You're joking... Someone with a Ph.D in CompSci can't answer these questions? - Robert S. Barnes
Not joking. Yes, it was shocking. - Kristopher Johnson
Python 3.2: swap = lambda x: type(x).from_bytes(reversed(x.to_bytes(length=2, byteorder="big")), byteorder="big") - Janus Troelsen
(2) return (in << 8) | (in >> 8); //because i actually took this interview - reuscam
8
[+10] [2008-09-08 20:15:46] Greg Dan

What is the difference between pointer and reference? Please describe the two main differences.


(5) References can't be reseated, and therefore must be initialized with a reference. - Corin
References can't be incremented/decremented by any amount, unlike pointers. - Donotalo
(3) To access the data, pointers require 2 reads from memory, one to fetch the value of the pointer, a second to fetch the data pointed to. References are like regular variables and require only a single read from memory to get their value. - Robert S. Barnes
(2) @Robert That doesn't seem right. My understanding was that references are pointers under the covers, they are just a bit more user friendly to programmers. If this is true then they would require 2 reads just like pointers do. - Evan Moran
9
[+8] [2008-09-08 19:13:24] Espo

These pages has over 40 examples of C++ interview questions:

http://www.techinterviews.com/?p=238

http://www.techinterviews.com/?p=340


(3) The question was "what's your fave?" not "where can I find over 40?" - Kate Gregory
10
[+8] [2011-03-02 07:49:14] Tony Delroy

From the similar beginner-specific question C++ areas you look for during interview [1]...

I've found myself dividing C++ interview questions into certain categories. Of these, many interviewers only touch on fundamentals and details. Junior candidates can only be expected to know some of this, but you definitely want to see that they've attacked it with some enthusiasm.

It's hard to find people who've made a systematic, broad investigation of the how-tos of C++ programming at the low-level library level (where the most ingenuity is generally required), and equally hard to find people who know what to do in terms of large-scale design and architecture trade-offs. Very roughly - just to illustrate these factors - I've compiled some examples:

  • FUNDAMENTALS: basic knowledge you must have to use the language
    • the what, how, why of class, object, pointers, functions, headers, templates, virtual functions, const & mutable, stack/heap, static...
  • DETAILS: the stuff that's normally just below the surface but occasionally gives rise to questions (the kind of stuff needing an answer from the C++ FAQ lite)
    • what're the performance/memory implications of inlining, of virtual dispatch...
    • throwing from destructors
    • Liskov Substitution Principal
    • RAII
  • HOW TO: generic practical programming tasks that even good programmers might not be able to do fully off the top of their heads, but should be able to be helped through with minimal pain - sorts the reusers of canned solutions from those who understand the implementation issues, e.g.
    • variants
    • functors
    • SFINAE tests for member functions
    • hash table or binary tree
    • thread pools
    • simple design patterns: visitor, observer, pub/sub, factories etc.
    • how do you debug certain types of issues: race conditions, deadlocks
    • multiple processes want shared in-place access to objects in shared memory: how can you provide runtime polymorphism (virtual dispatch) for the objects
    • design a non-templated function f(X&) and template <class A, class B> struct T such that f can accept any object of type T and handle them via virtual dispatch
  • WHAT TO: stuff that requires practical insight/experience: for example...
    • contrast the utility of templates and virtual dispatch
    • discuss approaches to serialisation/deserialisation in C++
    • compare Design By Contract with Defensive Programming
    • discuss physical dependencies (changes triggering/needing recompilation)
    • contrast factors in / approaches to testability: e.g. templatised code, abstract interfaces, derivation versus composition, #ifdefs
[1] http://stackoverflow.com/questions/347793

11
[+4] [2010-02-09 11:38:26] Dror Helper

I like the simple things that shows basic understanding of the language:

  • What is the difference between class and struct?
  • When (and why) should you use a virtual d'tor in a class?

(1) 1. Struct has public access by default (class has private access). 2. When you are going to inherit from that class. - Vlad the Impala
Another difference between struct and class can be shown if you try to declare struct MyClass; or class MyStruct; Both keywords are not interchangeable in declarations, not just for class/struct definitions. - BenoƮt
12
[+4] [2008-09-16 22:35:33] Denice

This is the one that I was given when I interviewed:

Given a singly-linked list that contains a character, you have to print the linked list in reverse order. You are given the head pointer, how would you go about solving the problem.


(1) Put the elements into a stack and then print them from them stack. - grigy
(9) "that contains a character" - no need to reverse the list :) - dionadar
(1) Obscure wording for the win. If it contained more than one, you could do it recursively, it's not at all harder. - Michael Foukarakis
@grigy: That only works well if you've already got a stack object that will automatically resize when you run out of space. - Robert S. Barnes
The answer to this question really depends on what tools you've got available. Do you have access to the STL and it's containers or do you need to code the answer completely by hand? - Robert S. Barnes
13
[+3] [2008-09-08 19:22:56] Ben Collins [ACCEPTED]

Write a simple custom memory allocator for std::vector and for std::list. This checks applicant's:

  • knowledge of STL
  • knowledge of templates
  • knowledge of inheritance
  • possibly knowledge of containers
  • if you make him be complete, this will also draw out his knowledge of some toolchain
  • most importantly, their problem-solving and multi-paradigm software design skills

I should add here, in response to a comment, that the point is not to see them write an error-free, compilable implementation on a white board. The point is to check that they are comfortable with the syntax and style of the language, comfortable with some advanced but important concepts, and see how well they think through a problem. Most people, as Drew notes, will never have had a need to write a custom allocator. That's good! That means it's a problem whose solution they won't likely be able to regurgitate from experience. I want to actually see them solve a problem before my eyes.


(4) Isn't that a bit hard? I mean, this would be really easy to goof in an interview situation. - Daren Thomas
I suppose it's hard. Its value depends on what you're trying to get from them in the interview. If you get all the way to a complete, compilable set of sources, then great....but I would be looking for is some indication that the applicant has the slightest idea of how to go about this task. - Ben Collins
Any chance you could link to some resources explaining how to do this? - Corin
(85) I disagree--custom allocators are pretty obscure in many domains--I think you'd filter out some pretty good candidates, unless you're willing to give them a lot of coaching with their answer. I've been using the STL for 12 years now & have never had a need for a custom allocator! - Drew Hall
I don't think coaching wouldn't be allowd - and the obscurity is half the point. I want my candidates to think through a solution in my presence. Observing them regurgitate something they know by heart from experience doesn't tell me anything at all about their problem-solving skills. I wouldn't even mind giving them a printout of the vector and list headers. - Ben Collins
(4) I disagree too, custom allocator is something I'd do maybe once or twice. I certainly have better things to do that swot up on the contents of Google just for an interview to answer questions I will probably never use again. - gbjbaanb
You guys are missing the point entirely. A custom allocator, while not something you'll actually implement very often (if ever), is really just a good intersection of C++ concepts you'll want your new hires to understand, and a perfect test case to see them apply their design skills by mixing the various techniques in the right ways. If someone came to my interview stuffed with recently reviewed info from Google on allocators, I'd ask a different question. An interview that draws out regurgitations of information is useless. - Ben Collins
(2) For C, a reasonable question is to ask them to implement strlen or strncpy or some such - it's really the same idea. You'll never, ever need to implement strlen or strncpy. You just won't. But it's a decent interview question because it touches on a handful of important issues for C developers (array handling, maybe pointers, memory management, strings). Since C++ is more complicated, then it only stands to reason that a question that similarly represents a cross-section of the important language concepts would be more complicated. Hence, a custom allocator. - Ben Collins
(1) you'd never know if they swotted up or not! Really, ask them the difference between map and list, that'll get rid of enough of the poor ones without having to hire only rocket scientists :) - gbjbaanb
what is "swotted"? - Ben Collins
(1) "swotted up" is British slang meaning to learn something (usually quickly) prior to a test. - 20th Century Boy
(6) Isnt that a much? If the applicant had reference to STL and was applying for senior level it may be a good question. But without reference... how is one suppose to remember all the typedef needed and methods required that is used behind the scene while the user happily uses the container. - acidzombie24
(1) @acidzombie24: I said I'd provide a reference. - Ben Collins
(15) I have writen my own allocator several times. I wouldn't be able to do it in an interview, and not without checking how I did it last time. Interview questions just turn more abnoxious each day, does one doctor go to an interview and asked for a heart surgery demo? I think we have lost the north in IT. Just hire the guy if he seems fine for the job, and fire if he can't code after a few weeks. - piotr
@piotr: If you couldn't write a simple allocator in an interview with a reference handy and without worrying about whether it compiles, then you're not fine for the job. I don't need to go through the pain of onboarding you as a full-time employee and then paying you for a few weeks to find out if you can code. I think all the consternation about the obscurity of the problem really misses the point - most of the difficult programming problems that come up are obscure. If you can't tackle an obscure problem with the help of a reference, then you're not "fine for the job". - Ben Collins
(3) @Ben Collins: certainly depends on the reference available. But writing an allocator is a very specific, idiomatic, seldom needed task, If I were interviewing I'd make sure the programmer knows more useful and day-to-day and useful techniques for real coding rather than solutions to obscure problems. When to use which STL container, how is memory allocated, smart pointers etc. I think asking about placement new and some templates questions would give the same information in a less obnoxious way. And no, real programming is not about obscure problems, is about making simple things simple. - piotr
(2) @piotr: I respectfully disagree with most of that. For the purposes of my interview, I'd provide any reference the candidate would ask for. The reason I particularly like this question about the allocator is because it's seldom needed, and I'd be likely to see my candidate actually solve the problem rather than regurgitate something. Memory allocation, smart pointers, and placement new are germane to the problem, as are the ideas of policy classes for template arguments, and how/when to use which STL container. This question touches a broad cross-section of topics, which is why I like it - Ben Collins
(1) This is, leniently, horrible. It's worse than delivering algorithms on paper for uni finals. I wouldn't want to work with anyone that felt asking me this on an interview is somehow acceptable. - Michael Foukarakis
@BenCollins: at what experience level would you think a candidate should be able to answer this question? Junior, Mid, Senior? - Gravity
@Gravity I wouldn't expect much of an answer from juniors. For a junior, it would be more of an observation of how they deal with something completely out of their depth. I think a reasonably experienced "mid" should be able to at least point to the right places in a standard library reference doc (look - there's a template class for allocators, so I guess I'd implement a class). - Ben Collins
@BenCollins Good to know. - Gravity
14
[+2] [2008-09-08 19:41:44] codingthewheel

One of my favorites is to ask the applicant to write code to shuffle a deck of cards. This is one that sounds easy, but is difficult to get right. See Atwood's The Danger of Naivete [1] and see also How We Learned to Cheat at Online Poker: A Study in Software Security [2].

[1] http://www.codinghorror.com/blog/archives/001015.html
[2] http://www.cigital.com/papers/download/developer_gambling.php

15
[+1] [2009-02-13 21:51:56] AndrewCr

I wrote a blog post [1] on this subject, before I discovered this question here. I argue that the specific question is not the important thing. It's a small piece of the overall technical interview.

[1] http://andrewcraze.com/blog/index.php/2009/01/what-is-your-favorite-technical-interview-question/

16
[+1] [2010-07-19 06:15:03] Donotalo

One of my favourite question is:

What is the answer of F + 1, given F and 1 are hexadecimal numbers.

This can be extended to n-base numbers.

[EDIT: I think what I've commented for Robert, should've put into original]

It tells me that the person I'm interviewing can understand hexadecimal, or can think about number system outside decimal. Yes, it is fairly basic, yet I've found candidate who cannot answer this question. Or struggled answering it.


(1) What does this question tell you about the programmer? It seems fairly basic. If you only have 4 bits of precision, then it overflows and the answer is 0x0. If you have 5 or more bits available then it's 0x10. - Robert S. Barnes
It tells me that the person I'm interviewing can understand hexadecimal, or can think about number system outside decimal. Yes, it is fairly basic, yet I've found candidate who cannot answer this question. Or struggled answering it. - Donotalo
17
[+1] [2011-03-01 09:10:27] Siddiqui

Write a program which take a integer value (n) from user and calculate the sum of 1 to n. The time complexity of program should be 1.


That's a math problem more than a programming problem. - Robert S. Barnes
(1) @Robert S. Barnes, I think good programmer should be able to solve the mathematical problems. Because without using math you could not write the optimized code. - Siddiqui
18
[0] [2009-02-14 12:21:27] Luc Hermitte

I did reply there [1].

[1] http://stackoverflow.com/questions/347793/c-areas-you-look-for-during-interview/347845#347845

19
[0] [2009-04-26 01:05:55] R Caloca

For professional games programming: I like to ask a mix of high-level questions (OOP, class design, etc) and low-level questions (write a function that performs endian change, write an Align() function, etc). Some people have the low-level skills but choke on the high-level (so these people are good are optimizing and finding obscure bugs) and then other people know a lot of OOP, UML, etc (so they are good for architecting modules)., but they don't know what happens 'under the hood'.


20