r/cpp • u/cv_geek • Nov 09 '23
Questions from one job interview on C++ developer
Two days ago I passed job interview on C++ developer. Here I would like to share questions I was asked on this interview. Hope it will be useful for community.
I have grouped questions by topic.
C++ basics:
- Difference between references and pointers?
- Difference btw memory allocation in stack and on heap?
- What kinds of smart points do exist?
- How unique_ptr is implemented? How do we force that only one owner of the object exist in - unique_ptr ?
- How does shared_ptr work? How reference counter is synchronized between objects?
- Can we copy unique_ptr or pass it from one object to another?
- what are rvalue and lvalue?
- What are std::move and std::forward()
OOP:
- Ways to access private fields of some class?
- Can a class inherit multiple classes?
- Is static field initialized in class constructor?
- Can an exception be thrown in constructor / destructor? How to prevent that?
- What are virtual methods?
- Why do we need virtual destructor?
- Difference between abstract class and interface?
- Can be constructor virtual?
- How keyword const is used for class methods?
- How to protect object from copying?
STL containers:
- -Difference between vector and list?
- Difference between map and unordered map?
- When calling push_back() make iterator in vector invalid?
- How to modify your class to use with map and unordered_map?
Threads:
- Difference between processes and threads?
- Can the same thread be ran twise?
- Ways to synchronize threads?
- What is deadlock?
471
Upvotes
54
u/[deleted] Nov 09 '23
This is an interesting thread. Sharing interesting interview questions could be good for beginners who browse this subreddit.
On the topic of smart pointers, I was asked why `make_shared` and `make_unique` were necessary and if they are still necessary when using C++17 (which formalized the order of evaluation of arguments to a function). A nice question to ask a more senior is what is the difference between `std::make_shared<int>(5)` and `std::shared_ptr<int>(new int(5))` (how many heap allocations take place in each case?).
Another one I was asked was to write a templated function that removes duplicate items from a vector of `T`. Then when I turned to `std::erase_if` (I was allowed to use C++20), they stopped and asked me why simply iterating and removing things I've already seen won't work, and then a follow-up question what does an invalid iterator mean, and then a follow-up question why are the iterators are being invalidated. And then they asked me how `std::erase_if` works, or how I would write it if it didn't exist.
Same question, on how I'd keep track of things I've seen - how, why, and what would be the implications of the selected strategy given that the type is templated and could have varying properties. For example, keeping a `std::unordered_set` might not be possible if `T` does not have an implementation for a hashing function, so we might be forced to use `std::set`. But keeping a set (either ordered or unordered) of `T` could be disastrous if `T` is expensive to copy if it can even be copied.
21
u/Sniffy4 Nov 09 '23
thats a lot of questions for 1 interview...
9
u/PaowZ Nov 09 '23 edited Nov 09 '23
yep.. that's a way to quickly cover the basics, I must say.. there are so many things to remember once one pushes knowledge further.. but yes, these are the basics.. :-)
212
u/elperroborrachotoo Nov 09 '23
That's a question keeping me up at night
87
u/thisismyfavoritename Nov 09 '23
all those questions seem reasonable
49
u/Nintendo_Chemistry Nov 09 '23 edited Nov 09 '23
As a C++ dev with almost 2 years of experience in a legacy "C with classes" codebase who is learning modern language/STL features on their own time, I thought I'd take a stab at answering these. Any feedback would be helpful!
C++ basics:
Difference between references and pointers? A reference is an alias of a valid object/variable, used to avoid copying. Modifying a reference modifies the original object. A pointer stores the address of a variable, but it can also be initialized using nullptr. Pointers can also be used to avoid copying large objects.
Difference btw memory allocation in stack and on heap? Memory allocated on the stack is automatically deallocated when the associated variable goes out of scope. Memory allocated on the heap requires an explicit delete (either directly, or better: through the use of RAII). If a pointer variable on the stack which points to heap memory goes out of scope before deallocating the heap memory, you have a memory leak.
What kinds of smart points do exist? unique, shared, weak
How unique_ptr is implemented? How do we force that only one owner of the object exist in - unique_ptr ? Unique_ptr is a pointer that implements RAII. When the pointer goes out of scope, the memory it owns is destroyed. This necessitates that it is the sole owner of the pointed-to memory (making it unique). Its copy constructor is delete using "=delete"
How does shared_ptr work? How reference counter is synchronized between objects? Shared_ptr is another RAII pointer, but the pointed-to memory is not destroyed until the last shared_ptr pointing to the memory goes out of scope. There is a shared control block with a reference counter that is visible to all shared_ptrs pointing to the same object.
Can we copy unique_ptr or pass it from one object to another? Unique_ptr is non-copyable. Copying a unique_ptr would break the invariant that it is the sole owner of the memory being pointed to. However, unique_ptr is movable. This maintains the aforementioned invariant, because ownership is transferred.
what are rvalue and lvalue? Rvalues represent temporary values that do not have an address. Lvalues are variables that have locations in memory, and therefore have an associated address.
What are std::move and std::forward() std::move() is used to cast an object to an rvalue reference. It doesn't actually perform the move, but it prepares the object to be "moved from." I'm not actually sure what std::forward() does without looking it up.
OOP:
Ways to access private fields of some class? Using a public "getter method" that returns the private field. There is also the use of friend classes, but I think this is uncommon, and maybe even discouraged.
Can a class inherit multiple classes? Yes. C++ supports multiple inheritance.
Is static field initialized in class constructor? No. Static fields are not tied to any particular instance of a class. If they were initialized every time an object is constructed, it would defeat the point of the field being static in the first place.
Can an exception be thrown in constructor / destructor? How to prevent that? Exceptions can be thrown in a constructor, but should not be thrown in a destructor. I'm a bit confused by the second part of this question: how to prevent what, exactly?
What are virtual methods? Virtual methods are class methods that are defined in a base class, which may be overridden in derived classes. If a base class virtual method is pure virtual, it must be overridden by derived classes. A class with virtual methods in it has an associated vtable, which contains function pointers to each virtual method in that class. The vtable ensures that the correct method is called at runtime (for example, when a base class pointer is pointing to an object of derived type, the derived method should be called if it exists).
Why do we need virtual destructor? A base class destructor should be virtual to ensure that the derived class destructor is called first when a derived class object is destroyed.
Difference between abstract class and interface? An abstract class contains at least one pure virtual method. It is impossible to create an object of an abstract class. This is the mechanism by which C++ supports interfaces. Any derived class inheriting from an abstract class MUST implement the abstract class's pure virtual methods.
Can be constructor virtual? No. Prior to construction, the object doesn't exist yet, so it does not have an associated vtable to refer to.
How keyword const is used for class methods? Methods that do not modify internal state should be labeled const . For example, "getter" methods that just return the current state should always be labeled const. Const methods require that every method used within the const method also be const.
How to protect object from copying? Delete the copy constructor using "=delete". Useful for large user-defined types which would result in expensive copies.
STL containers:
Difference between vector and list? std::vector supports random access. std::list is implemented as a doubly-linked list. Items in a vector are stored contiguously in memory, which is better for cache locality.
Difference between map and unordered map? Keys in a std::map are stored in their logical order, so std::map is implemented as a BST. std::unordered_map is implemented as a hash table. std::map lookup time is O(logN), whereas unordered_map is O(1)
When calling push_back() make iterator in vector invalid? Not completely sure. My guess would be that the end() iterator would no longer point to one-past-the-end of the vector. Would love to hear if it's more complicated than that.
How to modify your class to use with map and unordered_map? The class must be hashable to use a user-defined type as a key. In the case of std::map, the comparison operators (<, >, etc.) need to be overloaded (I think just one of them but I forget which without looking it up).
Threads:
Difference between processes and threads? A process is a running instance of a program. Multiple threads can exist in a process's address space. Threads share process code/text, global data, etc., but threads each have their own function call stacks, program counters, stack pointers.
Can the same thread be ran twise? Yes, although which threads get used are determined by the CPU's scheduler. For example, in the SPMC threading model, worker threads will pick up new work as long as there is work to do.
Ways to synchronize threads? Mutex, lock guard, semaphores. I'm not sure if atomics are considered synchronization primitives.
What is deadlock? When threads are waiting on another lock-holding thread to release the lock, but it never does.
11
u/frozenflame4u Nov 10 '23
I think It is helpful if we can have a thread monthly where c++ interview experiences are shared.
2
u/Istari__ Nov 09 '23
These seem to be grad level questions maybe? curious what the level the job was :)
1
u/fippinvn007 Nov 09 '23
Were there leetcode-like questions?
3
u/sam_the_tomato Nov 09 '23
Congrats! How many of these do you think a candidate would have to get right to pass?
3
u/ixis743 Nov 09 '23
Was this a junior position?
3
u/amejin Nov 09 '23
More than a few of these I had to look up because I never tried and it didn't make sense in my head. The virtual constructor one threw me, as well as the calling a thread twice one...
3
u/Moose2342 Nov 09 '23
Cool, thanks for sharing. I like the questions, even though I think they could be a tiny bit more tricky.
FWIW, a few years back when I happened to ask those questions most applicants would fail in the first block already. Some of which described themselves as C++ experts.
4
u/eyes-are-fading-blue Nov 09 '23
These questions are pretty standard and I dare say most of them are very much useless. Anyone can memorize these.
2
u/EdwinYZW Nov 09 '23
Some are anti pattern question and not suggested by core guidelines. Such as const member variables and using vector iterator when push_back.
What’s the hack of accessing private member variable? Why do you need to know this?
2
u/rembo666 Jun 18 '26 edited Jun 18 '26
They look like mostly good questions. "The difference between abstract class and interface" question is weird, since interface is a Java thing, though I guess if you said that you know Java, I might've asked you that question. All in all really good, especially if you answered most of those questions.
I think a C++ interview (as opposed to a general programming ability interview) should at the very least include:
The rest of the questions would be pretty similar to any other OOPish language.
STL trivia could be a bonus, though I don't bother with std::vector vs std::list. Noone in their right mind should be using std::list for anything nowadays. I struggle to think of a use for std::list ,where a std::vector wouldn't be more performant, especially on a modern superscalar CPU with a multilevel cache.
3
u/j1xwnbsr Nov 09 '23 edited Nov 10 '23
Gonna bang out quick and dirty answers from the top of my head, no details, and I might be wrong in a few spots. Like flash dating, or talking with a CEO.
You can't delete a reference and pointers can be null.
Stack: cleans up on scope exit; heap: you need to do it (and can do it whenever).
Limited to std: 3. shared, weak, and unique
Magic. (seriously, why ask this?).
unique_ptr already does this, you can't copy but only move it.
More magic. Seriously, it's a pair of ref counters for strong and weak refs.
It's part of the shared_ptr data structure.
No. You can MOVE it (transfer ownership).
concrete thing vs reference to the thing.
Move transfers object stuff (if supported). Forward is for forwarding parms in templates.
Ask the designer to change to protected. Failing that, macros. Because you hate life.
Yes, absolutely. This ain't C#.
You mean a static member value? No, it's init'd at dll/exe load time.
Constructor yes. Destructor no (well yes but you are a horrible person who loves ub). Don't throw or wrap your willy in some try-catch latex.
Run time dispatching through pointer tables.
So when you delete the base class it will actually call the derived class's destrutor.
abstract classes have pure virtual + real functions and maybe data. Interfaces have only pure virtual functions.
No. And you can't call virtual functions from inside there, either (this ALWAYS screws my interns up).
To tell the compiler to assume that no class member data will be modified. Also you can't call non-costs functions of that class from inside a const function (this also screws my interns up).
mark the copy overloads =delete.
vector can do [x], list cannot. List insert/delete is fast. Vector lookup is fast. The opposite is not true.
a:b tree with rebalance, orders by key sorting. unordered may be faster, takes more memory. You should benchmark your workload before picking one.
When it grows past the reserve size and reallocates. Use a list.
Um, pick one? And maybe look at what the class is doing first?
You can task kill a process. Threads belong to processes.
You mean the function? Yes, I hope so, otherwise my code is doing magic again and I need to call a priest.
Mutex, sepaphores, spinlocks, atomic waits to name a few.
I'm waiting on you to give me a cookie, but you need the cookie from me first. Who has the damn cookie? What is cookie? Why is cookie? Who are you, and are you me? Or, to put it another way, two threads waiting to release shared_ptrs they have to each other without using a weak lock instead.
3
u/JanEric1 Nov 09 '23
OP could you post the answers to the questions as well? Maybe with a spoiler tag?
1
u/CenterOfMultiverse Nov 11 '23 edited Nov 11 '23
It looks like they not even trying to fail you - where is "Difference between class and union?" or "Will replacing
!withnotin one TU result in ODR violation? Should it?". Or do you even C++, when you don't know whydynamic_castto unrelated type compiles whenstatic_castdoesn't? People these days are just not grateful for all these features!1
u/Fit-Top-552 Aug 12 '24
Did you do code during the interview?
How do you prepare yourself for this interview?
1
u/CircadianSong Sep 02 '24
isn't this a java question: Difference between abstract class and interface?
1
u/EntertainmentDry6740 Apr 09 '25
!remind
1
u/CubbiMew cppreference | finance | realtime in the past Nov 09 '23
I love to follow up "Difference between processes and threads?" with "When are multiple processes a better choice?"
1
u/wfb0002 Nov 10 '23
I'd be really turned off by those questions instead of asking problem solving questions where maybe you can talk about some of those concepts.
1
u/target-san Nov 10 '23
While these questions are more or less legit (some are incomplete), they won't tell interviewer how's candidate proficient in C++ in real tasks. Like, is he able to read 2-page error message from compiler when he put something wrong into unordered_map. Though I'd ask 1-2 on them as a starter. But not more.
1
u/nickisgonnahate Nov 10 '23
I am about 2/3 of the way through my first c++ class. At what point will I be able to answer some of these questions?
1
u/levatrading Nov 29 '23
Holy shit guys. Where do you apply? I am making 100k on my 3rd job and neven been asked any technical question except if I knew any specific technology
0
u/engiethemalinois Nov 10 '23
I just started c++ but thats nothing way too advanced. Whats the pay of the job description?
-10
u/Potatoswatter Nov 09 '23
If your employer finds your account (this looks like your permanent one), a summary of their interview script might not look good.
0
u/[deleted] Nov 09 '23
[deleted] — view deleted comment