TradeWeb c++IV

100% QnA interview. No coding no white-board no ECT no BP no algo no data structure.

System is Multi-threaded VC++/MSSQL.

One technical interviewer only. (The other 2 are behavior interviewers.) He is a director and looks very technical. I have met perhaps 3 to 5 interviewers focused on the fundamentals of a language/compiler. They pick one of 10 important parts of a language (like java, c++ or c#) and try to determine how well a candidate understands the key details and the rationales.

Below, Q’s are questions from this interviewer. A’s are my answers/guesses.

Q1: let’s talk about non-virtual dtor. You said there are problems in deleting a subclass instance via a base class pointer. Show an example.
A: Eg: subclass holds some resources to be released in its dtor, but in our scenario only the base dtor is called. Subclass dtor is not invoked.

Q1b: if subclass dtor is invoked, does it always run the base dtor?
%%A: Yes guaranteed. See my blog.

Q1c: if a subclass dtor is virtual and you delete an instance via a subclass ptr, you said this is good and subclass dtor will run, so is the “virtual” unnecessary? What’s the difference virtual dtor  vs non-virtual dtor?
A: The dtor is still picked at run time (and slower), but yes in both cases the subclass dtor runs.  If your system is written such that you delete a subclass instance only via a subclass ptr and never superclass ptr, then drop the “virtual” to improve runtime performance.

Q3: Let’s talk about a static member function sf2() in class Base. If you have a reference to a Base instance, Can you call myInstance.sf2()?
A: yes

Q3b: if Base and Der both have a static method sf2()?
A: subclass sf2 tends to hide Base sf2. Static type of myInstance variable is used to determine which version is used.

Q3c: how about myPtr->sf2()? Obscure details that I don’t want to spend too much time on.
%%A: looks very odd, but if it compiles, then it’s static, never dynamic, binding.

Q4: when must you use the pointer “this”? Obscure details that I don’t want to spend too much time on.
%%A: ctor chaining? Actually chaining is supported in c++11 but not using “this”.
A: if there’s a field and a local variable of the same name, I use “this->” to disambiguate. CORRECT:) See
A: in my ctor (or method), i may want to print my address. Yes you can usually do that in the caller afterwards but not always
A (hindsight): Similarly, in my ctor (or method) I may want to conditionally save my address in some container. The conditional logic is not doable after the ctor.
A (hindsight): if I know the host object is in an array, I could do array arithmetic using “this” with precaution.
A: delete this. I have seen people doing it.
A (hindsight): CRTP
A (hindsight): if parent class has a const method m1() and non-const overload m1(), you can cast “this” to call either of them.
A (hindsight): what if inside a method you need to access a parent object field hidden by a host object field? Can you cast “this”? Yes tested but not a “must” use case. Alternative solution is B::nonStaticField
AA: sometimes you must return *this where the return type is HostClass&

Q4b: can you think of an example of using “this” to avoid access violation?

Q4h: why use ctor chaining even if it’s supported? Why not call a common (non-static) setter method s2() from multiple ctors of the same class?
A: that setter has to be non-static!

Q4i: You think ctor should not call a non-static method?
A: it can, but I don’t do it. The host object is half-initialized, so the setter method must strictly perform field initialization and nothing else.

Q5: why do people use class templates? Note — Interviewer didn’t ask function templates.
%%A: avoid the cost of virtual functions

Q5b: Let’s look at combining class hierarchy with templates.
A: not a good idea to combine them. STL has probably no virtual functions.

Q5c: Let’s see. You said you have a bunch of “payload” classes and you want to use a container of PL1 and container of PL2. Ok You said that’s a common use case of class templates unrelated to virtual functions. Suppose the container template requires each payload class to implement a method f2(). If f2 is provided by a base class, wouldn’t it be easier (can be virtual or non-virtual)?
A: If there’s a family of payload classes, like Shape, Rectangle, Square… then I feel it’s best practice to use a template of smart pointers. I think it reduces the risk of slicing.
A: if the payload classes don’t form a family hierarchy, then there is probably some template meta-programming technique to provide a default implementation of f2(). I’m no expert on template meta-programming.



We often call these “obscure details”. At the same level they are a small subset of a large amount of details, so we can’t possibly remember them all. Surprisingly, interviewers show certain patterns when picking which technicality to ask. Perhaps these “special” items aren’t at the same level as the thousands of other obscure details??

These topics are typical of QQ i.e. tough topics for IV only, not tough topics for GTD.

  • archetypical: which socket syscalls are blocking and when
  • some of the hundreds of g++ options?
  • hash table theoretical details? too theoretical to be part of this discussion
  • select() syscall
  • vptr

t_ivTechnicality is the tag

c++SCB eFX IV#Dmitry

100% QQ type, as defined in feel many are micro optimizations with questionable improvement. I wonder how much value such obscure knowledge adds to the team.

Q: Scanning a vector of int (like finding the average or max). Forward iteration vs backward iteration, which one could be faster, considering all possible compiler optimizations.

%%A: forward. Memory read into cpu cache will be in chunks, not one element at a time. Easy for forward iteration. Not sure about backward.

Q: Which one could be fastest:

void f(double arg){…..}
void f(double & arg){….}

%%A: inlining for first but not 2nd?
A: See esp. the long answer.

Q: Thr1 and Thr2 on 2 CPU’s both update an object s, having 2 fields. Thr1 only updates s.field1. Thr2 only updates s.field2. No interference. No synchronization required. We observe the performance is slower than using one thread to update both fields. Any explanation?
%%A: caching in cpu

Q: weak_ptr justification, when we have shared_ptr already? I feel [[effModernC++]] has a good chapter on it.

Ashish pointed out in some apps, you could identify a clear risk of circular dependency. Replace with weak_ptr.

Q: given an 2D array arr[10][5], how do you use pointer arithmetic to hit arr[1][5]

A: Contiguous. see Note this is different from an array of pointers.

Q: what would you see if a TCP socket server has a full queue
%%A: TCP requires handshake, so if server is unable to accept a request the client would know it.
%%A: connection refused?

Q: what STL algorithms did you use?
%%A: foreach(), find(), copy_if(), transform(), reverse(), sort(), replace_if, remov_if

c++method default arg isn’t saved]vtable #Ashish

Google c++ style guide forbids default args in virtual functions.

Ashish said he was asked a common question in multiple c++ interviews. The default arg value is “declared” in base class and (or) derived class but never saved in the vtable. It’s basically resolved statically, at compile time.

If you use a pointer to Base to invoke the virtual method, then the Base default arg value applies unconditionally, even though the subclass method is chosen at run time, via the vtable. Highly confusing.

c++iv: Jump#2 #overflow catch

Mostly QQ type of questions. I feel i may have to give up on some of the very low level (perf optimization) topics. I feel java and c# interviews are not so low.

Most of the questions are fairly … uncommon

Q: Stack overflow – who can detect it and print an error msg? JVM can do it but what if there’s no VM?

Q: What data type would you use for the tasks in a thread pool??
(I find this question too advanced. c++11 offers Futures…)
%%A: look at pthread-create. a func ptr taking a void ptr

Q: After malloc(), how do you cast the pointer to MyClass* ? Do you call the ctor? How?
(This is asked again by Alex of DRW)
A: placement-new?

  • Inter-thread communications in thread pool – how does it work?
  • Thread pool — Your resume mentioned your home-made thread pool? How?
  • Boost::any, boost::bind, boost::function
  • CPU cache – how do you use it to improve performance? Any specific techniques?
  • Stack size – who controls it? at Compile time or run time?
  • Shared ptr – how is it implemented?
  • Scoped lock – what is it, why use it?
  • Your bash shell customizations as a cpp developer?
  • $LD_LIBRARY_PATH — what is it?

c++ stream — IKM findings

——tellg and tellp? is a short explanation.

tellg(void) and tellp(void) both return their pointer’s position
ostream& endl (ostream& os);
stream::rdbuf() changes the filebuf…
endl – flush() implicitly
If your variable to “populate” is an int, then extraction operator stops when hitting ….”any character that couldn’t be part of an int” which is not limited to white space.
—-which stream classes can be used for writing to a file
——which ios modes are used for reading a file

c++ template technicality – IKM findings

Never quizzed when I declare I’m no template wizard…

to specialize a func template,

template <typename T> void fn(T a){}
template<  > void fn(char c){…} //empty param to specialize an existing func template

template<class T> void f(T arg){ cout<<arg<<endl;}
template<> void f<char>(char arg){ cout<<"char: "<<arg<<endl;}
// the <char> after f is optional !
int main() {
///////////////// Some<int> is distinct from Some<char> --
template <typename T> class Some{
  public: static int stat;

template<typename T> int Some<T>::stat = 10;
int main(){
  Some<int>::stat = 5;

select2perform/brain-bench c++ Q&A

Q: vector1.erase(remove(vector1.rbegin(),vector.rend(),someValue).base())

Q: To put 5 identical values into a vector,
std::fill_n() ?
std::fill() ?
Q: If class E virtually extends C and extends D, where C/D both virtually extend B, what’s the construction sequence?
AA: P1000 [[primer]]

Q: find intersection of 2 compatible vectors?
%%A: std::find_first_of()
Q: can you pass a float into a func(int) or func(char)?
AA: yes but if you cout in func(), it interprets and prints the object differently.
Q: can a non-static reference field be initialized upon declaration?
%%A: i don’t think so, reference field or nonref. The java-style quick initi is illegal for non-static.
AA: gcc allows java-style init only for a static AND const field.

Q: can you “extern” a prototype and then declare the same prototype again?
AA: legal

Q[u]:difference between “new Account” and “new Account()” with the parentheses?
A: subtle difference. See other posts on this blog such as

Q[u]: declare a pointer to a method accepting an int and returning void. Need to memorize the exact syntax
AA: void (Dog::*ptr2method) (int);

Q: my ex spec mentions std::runtime_error. Can I throw a range_error, or an std::exception, or std::invalid_argument?


Q: reverse print a string using copy to cout
AA: copy(str.rbegin(), str.rend(), ostream_iterator< char >(cout, ” “));
* The ” ” 2nd argument is not necessary, but I’d suggest we memorize just a single form of the ostream_iterator ctor, the 2-arg form.
* The type is char not  ptr-to-char

Q: using N1::f; f(); using N2::f; f();
AA: GCC complains 2nd all to f() is ambiguous. explains 

Q[u]: multiple inheritance dreaded diamond – what if one of the 2 “virtual” keywords is omitted? How many times will you call the base constructor?

Q[u]: anything wrong with
Base & var = static_cast(*(new Derived));
AA: legal in gcc.

[u = unimportant/trivial/unlikely to be issue in practice. Often compiler will inform you clearly.]

[11]Cantor/eSpeed c++ #manyQ

Mostly knowledge-based QQ questions. I need to be selective what to study.

Q1: The reverse is common but when do we provide c wrapper around c++ classes?
A: internal implementation is c++ but clients need C API

Q1b: can c call c++ # <—— very common question
%%A: at compile time, c++ code may be uncompilable by a c compiler. CFRONT converts c++ code into c source code until exceptions were added to the c++ language. At run time, if I have object code precompiled from c++, can c call it? I think it’s often possible.
A: check out the C Application Binary Interface. If your C and C++ code are interoperable, it is because your C and C++ compilers also conform to the same ABI.
A: yes that’s what extern “C” is for.

Q: tool for binary code dependency? (I guess the dependencies are dynamic libraries, rather than static libs linked in.)
AA: ldd or objdump. See

Q9: call java from c++, what’re the c++ function(s)?
A: create_vm(), CallStaticVoidMethod(), CallVoidMethod() etc

Q9b: How do I access an int field of a java class?
%%A: if I have a pointer to the java object, I should be able to directly access the int field

Q: how do u implement a singleton

Q: semaphore(1) == mutex?
%%A: no since semaphore in most implementations uses a mutex internally. Functionally they are identical
%%A: semaphore is often cross process. Mutex can also be used on shared memory.

Q: for a const method getAge(), can it return a ptr to a non-const int which is a field?
%%A: i have seen sample code, so probably compilable
A: tricky. P215 effSTL says that inside a const method, all non-static fields become const.

Q3a: what’s the return type of operator*()?
%%A: can be anything, just like operator[], but not void not empty

Q3b: How about qq[ operator T*() ] ?
A(now): is it the OOC to a ptr? Correct. See

Q: if Base class has a virtual method f(int), and Derived class has an overload virtual method f(float, char), is the Base f() accessible via a D object?
%%A: the D f() hides the base f(), but base f() may still be accessible using A::f()

Q: 1 process, 30 threads vs 10 processes * 3 threads each? Assuming there’s data sharing among the threads
%%A: avoid ITC and serialization
%%A (Now): I feel single-process has a single point of failure without redundancy.
A: depends on the IPC cost. If non-trivial cost then favor 30-threads.

Q: how do u change the default fair-share scheduling among threads? #<— uncommon
%%A: I can make some threads sleep or wait. I can control thread-lib-level priorities, but the kernel thread priority levels could be very coarse
%%A(now): if userland thread, then scheduling is done in the thrd lib.

Q: unix performance monitoring?
%%A: jconsole; top; vmstat; perfmeter


Q: Dynamic loadable library. How do we configure the system to load a new version of the library?
%%A: just overwrite the existing *.so file??

Q: how to convert a ptr-to-non-const to a ptr-to-const?
AA: just assign it. The reverse assignment needs const_cast. Tested in g++. I feel this is an obscure technicality.

— communication layer
Q: how do I see syscalls and sockets open by a process?
%%A: truss; lsof; snoop/tcpdump; netstat

Q: practical use of signals?
%%A: kill, core dump, thread dump, suspend,..
A: I used q(trap) to install my signal handler in my bash

Q: what are named pipe? #<—– uncommon
%%A: I think they exist in the file system as fake files. “cat | more” uses an unnamed pipe I believe.
A: now I think I should just say “never used it”.