# C++ Interview Questions

This topic is 2299 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey all,

Anyone of us who has interviewed for a game company (or any company in general) that focuses on C++ programming has probably had the "on the spot C++ proficiency test" in which they ask you to write some C++ program in front of the team.

This thread is in hopes that people will post what types of C++ questions or programs they have been asked in an interview. My hope is to practice a wide variety of potential questions so I won't look stupid in front of a potential employer. I'll start things off.

In an interview for a game company I was asked to write a function that will reverse a string without using the string class (i.e. use a null terminated char array).

##### Share on other sites
Here's a few I've seen asked:
* Test if a number is prime.
* Binary search.
* Compute the median of an array of integers.

I think Project Euler is a very good way to practice writing little programs that do clever things.

##### Share on other sites
Here is one I have had multiple times, although not phrased exactly the same way:

• Implement an RLE Compression algorithm (using either c-style string or std::string as input\output, this would depend on the interviewer they may even let you pick)

##### Share on other sites
Thanks guys! Please keep them coming. I'm definitely going to practice these problems. I think I would bomb a few of them if asked to do them on the spot.

##### Share on other sites
The one I used to ask was write a function that returns a count of all the 'on' bits in a byte parameter.

There are (of course) different ways of doing it, and (astonishingly) watching some candidates balk at the very idea of writing a C function was a little disappointing. I was really hoping at least one candidate would say 'well, why not just have a lookup table', but sadly it never happened...

As an interviewer it was much more interesting to me how they went about trying to do the problem than whether it was actually right. Plus, performance under pressure and all that...

##### Share on other sites
In an interview for a game company I was asked to write a function that will reverse a string without using the string class (i.e. use a null terminated char array).
I've seen that one, plus simple extensions like - for each word in the string, reverse the letters in the word, or, reverse the order of the words that make up the string, etc...

These kinds of questions are just to make sure that you're competent at basic, low-level programming concepts, like pointers and bytes.
In this category, you'd probably see other questions like, how would you test if the highest bit in a byte is set, or, how would you count the bits set in a word, or, how would you multiply a number by 8 without using multiplication, etc...

There's also questions that don't require you to explicitly write code, but say a lot about your ability to write code, like:
If you've got two classes that are dependent on each other (i.e. a circular dependency), how would you break this dependency?
Is inheritance useful for code-reuse?
What is the big-O complexity of inserting an item into a sorted array?

I was really hoping at least one candidate would say 'well, why not just have a lookup table', but sadly it never happened...
No one broke out the leet bit-twiddling skillz?
[font="Courier New"][size="1"]count = (((((v - ((v >> 1) & 0x55555555)) & 0x33333333) + (((v - ((v >> 1) & 0x55555555)) >> 2) & 0x33333333)) + ((((v - ((v >> 1) & 0x55555555)) & 0x33333333) + (((v - ((v >> 1) & 0x55555555)) >> 2) & 0x33333333)) >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;[/font]

##### Share on other sites
They ask for source code to reverse a linked list at Morgan Stanley, 2nd interview (just in case anyone was curious).
In the 3rd interview they ask you to make a date class which can print the month names and the number of days in each month, accounting for leap years. They tell you leap years occur and your job is just to make sure you implement that logic correctly.
You can also expect a lot of questions about design patterns.
There was only one question I could not get, and frankly to this day I still do not know the answer. I wish I could remember exactly how the question was phrased.

Other miscellaneous problems:
#1: Draw a BVH in 2D.
#2: Convert a string to an integer (manually).
#3: Pick a random number between 0 and 110 which is a multiple of 10.
#4: Given that the variables A and B are 32-bit unsigned fixed-point variables with 4-bit fractions, how many fractional bits will the results of each of these have?
-> A: A + B
-> B: A * B
-> C: A / B
#5: Given 2 axis-aligned boxes in 2D, outline an algorithm to determine if they overlap.
#6: Rewrite the following function so that the multiplication or division operators are not used and there are no loops:
int MultiplyInputBy123( int input_value ) { return input_value * 123; }

#7: Is C++ slower than C? Why or why not?

L. Spiro

##### Share on other sites

This comes up a lot: "When and why should destructors be declared virtual?"

Perhaps the toughest interview question is the one you know the answer to but the interviewer has wrong. ;^)

class BaseClass
{
public:
int X;
virtual void SetX() {X = 1;}
BaseClass() {SetX();} // <-- Call to a virtual function in the base class constructor.
};

class DerivedClass : public BaseClass
{
public:
void SetX() {X = 2;} // <-- The virtual function is also defined in the derived class.
}

int main()
{
DerivedClass DerivedObject; // <-- An object of the derived class is created.

// What is the value of DerivedObject.X ?

The interviewer thought (as programmers often do) that it was a clever question because he had stumbled upon it the hard way. I happened to know the answer. But he'd never really figured out what was going on when he ran into this problem, and he had (erroneously) come to the conclusion that the behavior was undefined.

Edited by vreality

##### Share on other sites
It's interesting how humbling computer science can be. Even after 4 years of programming I don't know that I could answer some of these questions with people standing over my shoulder and without using the internet for a quick reference. But that's what this thread is all about! I'm going to practice all of these and hopefully not choke at interview time.

##### Share on other sites
Hidden

This comes up a lot: "When and why should destructors be declared virtual?"

Perhaps the toughest interview question is the one you know the answer to but the interviewer has wrong. ;^)

 class Base { public: int X; virtual void SetX() {X = 1;} Base() {SetX();} // <-- Call to a virtual function in the base class constructor. }; class Derived : public Base { public: void SetX() {X = 2;} // <-- The virtual function is also defined in the derived class. } int main() { Derived MyDerivedObject; // <-- An object of the derived class is created. // What is the value of MyDerivedObject.X ? 
The interviewer thought (as programmer often do) that it was a clever question because he had stumbled upon it the hard way. I happened to know the answer. But he'd never really figured out what was going on when he ran into this problem, and he had the answer wrong.

After hearing his incorrect answer, I would explain why this is a special case, including the logic behind why this is a special case, and if he persists that I am wrong, I would finally say, “Okay, let’s make a deal. You check that on any compiler, and if I am right, I get hired unconditionally. If not, I pay you personally \$100.”

L. Spiro

" the one you know the answer to but the interviewer has wrong"

Frankly, it's amazing how common that is. One of the problems with these things is that all too often they degenerate into an opportunity for interviewers to make themselves feel better. And quite often they're over-reaching their own technical skills.

Fizzbuzz or reverse a string is entirely sufficient to lose the maybe 60% of candidates who actually can't program AT ALL[1]. Anything beyond that is frankly labouring the point; esoteric questions about the C++ spec are boring for everyone concerned and have no relation to work actually done. (It was amazing the amount of interviews I went to as an IT contractor which were all about weird tricky edge cases of C++ exception throwing, but when I actually started work there, the codebase doesn't use exceptions because the developers aren't confident enough at using them. And usually therefore they're banned...)

[1] What I find slightly bonkers is that a substantial number of these candidates actually think they are good developers and are surprised to find themselves struggling. It seems to stem from being in large matrix-managed teams where one can spend many many years being only borderline competent at developing without anyone noticing. The actual output of the team is caused by the work units being regularly and randomly swapped between members until (eventually) they're done by the one or two competent developers. In many industries this is normal working practice[2], and staff can truly believe they're contributing because the work units passed through their hands. Likewise I meet an amazing number of highly experienced OO devs who, on closer inspection, have actually spent many years going to meetings where some OO design got done... not *necessarily* by them.

[2] And the appallingly low productivity is (in a storming bit of double-think) considered normal because... well... software developers just actually aren't very good are they? Well, on average NO, they're not...

##### Share on other sites

" the one you know the answer to but the interviewer has wrong"

That's why I figured making it the point to be wrong. In short, it's a horrible piece of code essentially just appending one c-string to another.. except using all the awful things I've encountered in peoples code, from tacking every problem by typing "while(1) switch(x)" on autopilot, to the annoying "while(1) break, break, break" pseudo-goto, off-by-one bugs, non-descript names. The point is essentially to just ask "what is wrong with this code" and let him bash away (always hoping for "how about using std::string and += instead of this twisted mess?")

The only time I had an interested test to do was essentially "offline" (ie. they send you the questions and expect you to write back in finite time). Stuff like:

-The AI needs to navigate through x waypoints, implement the move function
-Optimize this code (if in nested loops to check if youre in the second half)
-Silly things (finish this linked list implementation, add 1 to unsigned int with only shifts and logical ops)
-Refactor this code

And my favorite, which I kept for not being one of those silly bit-fiddling questions (in summary):

Imagine a chess board as 8x8 columns of different height. Now imagine pouring water over it (which will of course drain off at the edge of the board). Describe an algorithm to calculate the amount of water the board can hold.

Implementation was not wanted, only a description of the steps. Of course after sending back the test I couldn't resist to create a simple OGL program to generate random boards, calculate the water level at each sell and render it for "visual verification".

##### Share on other sites
In a coding test I had to do sorting, binary search, and a quick pathfinding problem. I've had to read from a file and put it back in sorted order. I've had to create two signals and have them trigger one another (based on some criteria).

In interviews I get the 'reverse a null terminated string', 'now do it in place', 'now do it in place with no temporary' path pretty much all the time.

##### Share on other sites
I can't get into the details of real interviews I've had, because of NDAs and such, but here's a few generic things to be comfortable with:

• Basic algorithms: search, sort, and various applications of recursion
• Basic data structures: arrays, lists, trees, heaps, hash tables, etc.
• Tree/graph traversal methods - know the difference between depth-first and breadth-first and why each one is preferable in certain circumstances
• Pre-order, post-order, and in-order traversal is a good one to know as well
• Simple string processing at the byte/character level
• Elementary bit manipulations - at the very least, know how bitmasking and such work
• Simple analysis of existing code to find missing functionality
• Implementation of new functionality in a fixed, unchangeable code base

Last but very much not least, know how to describe your thought processes in detail and with precision. If you're given an hour to do a two hour job, do your best in 45 minutes. Spend the remaining 15 minutes documenting/explaining exactly where you could improve and why you chose the trade-offs you did. This is a common curve-ball to throw at people in my experience, so be ready for it.

Overall... if you can pick up someone else's code, modify it, and produce something that works, you'll probably be OK.

##### Share on other sites
Thanks guys. Theres a good bit of material here!

Sometimes I'm puzzled by how much is expected out of a programmer. I'm about to graduate from the University of Texas at Austin.... a top 10 CS university where they don't teach you C++ until you're final semester in an OS class, and by teach you C++ I mean have you write a few basic functions in C. Yet straight out of college we are expected to be professional C++ programmers. Luckily I have worked with C++ quite a bit in my free time, but I haven't had the opportunity to program in nothing but C++ for a few years to really master the language.

Outside of the language we have these data structures, bit manipulations, and random algorithms that you learn once and only use on a blue moon (at least in college) and then are expected to know off the top of your head. I don't know how anyone could do it without having years of professional experience or spending a few weeks before interviews memorizing every potential question.

Majoring in CS is generally much more demanding then most majors and then we are expected to go above and beyond that in our free time. I guess were not allowed to get exercise or have lives =)

I guess that's why some people get paid the big bucks. I'll just have to prepare as much as I can and hope for the best.

##### Share on other sites
You should've perhaps specified what sort of position you were looking for example questions for (or perhaps we should've).

I suspect a lot of the people here didn't get these questions when they interviewed as entry level devs. And the tone of interviews varies a lot depending on your industry and even location. Up here in Minnesota, you're lucky to get any technical questions at all. Out in silicon valley, even the most laid back company still has a fairly rigorous technical gauntlet.

##### Share on other sites
Apoch has had the best answer so far. The point, after all, is not to memorize clever answers to a few popular problems, but to have a solid grasp of the wide range of fundamentals that these TYPES of questions are meant to evoke. Besides, a good interviewer will recognize a recalled answer, rather than one which is truly being thought out, even if you fake the discovery aspect. Honestly, if you get a question you already know, that should be the first thing you reveal to your interviewer. They may ask you to do it anyways, in which case you want to show that you understand the solution you have (and also that you are sure there are no holes in it.)

In addition to algorithm-ish stuff, also know basic oop and language stuff -- what are the 3 pillars of oop? What are the 3 kinds of inheritance and under what situations are they useful (properly used, not how they work)? What is a 'volatile' variable, and what's an example of when you might use it? Describe how 'public', 'protected', and 'private' affect member visibility. Know what 'static' means in all the various contexts it can be uses. Those types of things.

##### Share on other sites

You should've perhaps specified what sort of position you were looking for example questions for (or perhaps we should've).

I suspect a lot of the people here didn't get these questions when they interviewed as entry level devs. And the tone of interviews varies a lot depending on your industry and even location. Up here in Minnesota, you're lucky to get any technical questions at all. Out in silicon valley, even the most laid back company still has a fairly rigorous technical gauntlet.

Haha, good point. I'm hoping to get into the gaming industry as that is what I spend most of my free time working on and have the most experience with (and of course what I am passionate about). This of course means strong C++ skills required. In my free time I made a WebGL/JavaScript engine which has a lot of basic 3D game engine functionality www.cs.utexas.edu/~josh4689 (feel free to criticize). I feel that I have a pretty solid foundation about how the basic mechanics in a game engine work. Plenty of experience with vector/matrix math, basic lighting techniques, basic skin-and-bone animation, simple terrain (with GeoMipMapLoD), bounding volumes, quite a few intersection algorithms, picking, most of the basic geometry used, view frustum culling, and parsing Collada files.

Unfortunately most of the big companies don't seem to be interested in hiring an entry level software engineer. Bungie has a few openings I feel I am qualified for. Keeping my fingers crossed.

##### Share on other sites
You should have been born in Japan. Here, they almost only hire out-of-college kids. Before you even graduate you already know at which company you will be working, and you will work there for basically your life.

That being said raises a point. You don’t have to seek only within America. I started my career in video games overseas. Keep in mind that the world is your oyster, not just your country.

L. Spiro

##### Share on other sites
Heh. While I am a big anime fan, I'm also 6'2. I would stick out like a sore thumb! On a side note, could one only speak english and still work over there?

##### Share on other sites
It is possible, as I know many who are doing it.
But Japan is not where I would start. This country is very exclusive and it is practically unheard-of to hire someone from overseas who does not speak the language and is just getting out of school.
You would need a fairly hefty resumé to be recruited from outside of the country.

Other countries to consider: Sweden, England, France, Germany, Malaysia, China, Hong Kong, and Thailand.
Few people realize that southeast Asia is trying to get into the gaming industry, and foreigners are considered welcome. The Malaysian government makes game companies tax-exempt.
You have a chance at Game Brains in Kuala Lumpur. Their office used to have a nice view from the 60-something’th floor of the Petronas Towers, but they have since moved.
You have a good chance in Thailand at Lumai Prod or Sanuk Games. Both are run by French people who speak English. Thailand and Malaysia are countries where it is absolutely not necessary to speak the native language to live there.

L. Spiro

##### Share on other sites
On 10/6/2011 at 7:07 PM, Ravyne said:

The point, after all, is not to memorize clever answers to a few popular problems, but to have a solid grasp of the wide range of fundamentals that these TYPES of questions are meant to evoke. Besides, a good interviewer will recognize a recalled answer, rather than one which is truly being thought out, even if you fake the discovery aspect.

I think having a solid grasp on the fundamentals was assumed here (what to do if you don't is a whole other topic). And the performance anxiety being expressed was mostly about the rather silly spectacle of "programming" on a white board for an audience. It's a valid concern, being that it's not something you would get good at in the normal course of studying or working. And practicing, on typical interview questions, is a decent idea.

It's not as if being in practice is going to fool anyone into thinking you know something you don't, or can reason about something you can't, but as the OP pointed out, it can keep you from looking like you know less than you do. The less of your brain that's occupied by the mechanics and novelty of the performance, the more that's free to think about the topic in question.

[Think driving a car or counting cards. You can certainly do either without ever having practiced, but they take all of your concentration, and you probably can't carry on an intelligent conversation at the same time. But with practice, they take almost none, and your brain is free for higher level thinking. The same sort of thing holds for whiteboard performances, to a lesser degree.]

As for already knowing the answer to a question, it's bound to happen, and only serves to show the weakness of the puzzle approach to interviewing. But the other weakness of interview puzzles is that they can sometimes make a promising engineer look bad. Seems better to err on the side of, "Oops, I knew all the answers."

Edited by vreality

##### Share on other sites
Interviews are a good place to learn as well. Practice as you might, you will never be fully prepared, but don’t take it so hard if you fail. You will have learned from it.
The largest jumps I have made as a programmer were due to questions asked in interviews.

Morgan Stanley was interested in design patterns quite a lot. I knew them by name, sure, but only started integrating them into my own work after I realized Morgan Stanley thinks they are important. Prior to the Morgan Stanley interviews I was not so strict on const correctness. Afterwards I was 100% strict.

At Square Enix I was asked if I used shared pointers/smart pointers. When I replied with No, he asked why. I realized then I didn’t have a good reason for not using them.
I started using them afterwards and now I am wondering why I didn’t start sooner.

L. Spiro

##### Share on other sites
The most interesting one, and frankly the one that I enjoyed the most (because I am weird) was when I was asked to basically write a C++ integer library that used ASCII strings to store the numbers and perform operations. I was graded on functionality and efficiency. I would have much rather written a bit-based solution, though (arrays of integers).

##### Share on other sites
I never said there's no value in practicing, I said there's no value in knowing the answers to specific questions. There very much is value in practicing whiteboard coding (eg. On a sheet of paper with no IDE or reference material) and it can be a good idea to work through some common problems in order to get into that headspace. I do both when I'm on the hunt, as well as writing down my answers to non-technical questions (because I find that it helps me to collect my thoughts on the matter so that I can more easily recall the key points later.)

But, you'd be unwise to assume that even experienced coders are versed in the basics, left without their IDE and no Wikipedia. The noobs rarely even know what the basics *are* and the experienced often take for granted that the *just know* all there is. Its also often the case that the basics underpin your understanding of the problems given, and if you've built your answer on top of a shaky, assumed foundation, you're likely to find that it collapses in a stiff breeze.

As a recent grad, you're expected to have a solid grasp of algorithms and data structures, decent command of one or two languages (and knowing the fundamentals of them), probably some idea of design patterns (or at least enough intuition to stumble into them, even if you didn't aim for them), to be able to think through problems, to be eager to continue learning (not a know-it-all), and to be a good culture fit with the existing team (both interpersonally, and to some extent technology-wise). Anything more than that is gravy.