TS Interview

Not-so-easy C++ interview.

1) Can a class with a private destructor be instantiated?

That is a tricky question because the answer is both yes and no.
Yes, it can be instantiated on a heap.
No, it cannot be instantiated on a stack.

A class with a private destructor cannot be instantiated on a stack (Object obj) because the compiler cannot call a destructor.
It is okay to instantiate it on a heap because we control when the destructor is called.
A class with a private destructor can destroy itself (delete this).

So when do we need a class that has no accessible destructor?
A class that counts references should not be deleted by a user because the user does not know if all references have been released.

2) What is a function object (FUNCTOR)?

An object that overloads the function call operator ()

class compare
    bool operator()(int A, int B) const
        return A < B;

And here is a usage pattern:

template <class Functor>
void sorta(int* items, int count, Functor pred);

3) Find n-th, from the tail, object in a linked list.

The question can be easily solved in O(n) time with two pointers.
Start the second pointer n iterations after the first pointer.
Once the first pointer has reached the end of the linked list, the first pointer is at n-th element from the end.

4) Implement a URL caching mechanism

Cache speeds up fetch requests by storing results in fast memory.
All practical cache algorithms, sooner or later, must expel items from cache.
Least recently used (LRU) algorithm simply evicts items that are least used. LRU is frequently implemented using a priority queue.
CLOCK algorithm is implemented using an array and it evicts the first unused item that it finds.

5) How do virtual functions work?

A v-table is constructed for each class that has virtual members.
V-table contains addresses of all virtual functions, and is created when a class is instantiated.

6) Is it possible to have a virtual constructor?

No, because the v-table is not yet available when the constructor is executed.

7) What data structures would you use to store a dictionary of names?
8) What is template metaprogramming?

Metaprogramming is the ability of a program to manipulate other programs as data.
Metaprogramming is frequently achieved via reflection or templates.

Here is an example of metaprogramming in C++:

template <int N>
struct Factorial
    enum { value = N * Factorial<N - 1>::value };

template <>
struct Factorial<0>
    enum { value = 1 };

void fact()
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1

9) Is there a performance difference between a) and b) loops?

a. for (unsigned int i=0; i<10; i++)
b. for (unsigned int i=0; i<10; ++i)

10) Define a Singleton

class Singleton
    static Singleton *instance (void)
        if (instance_ == 0)
            // Critical section.
            instance_ = new Singleton;
        return instance_;
    static Singleton *instance_;

Leave a Reply

− 2 = six