Monday, December 6, 2010

Typical UNIX C++ interview questions

C++ :


The compilation process : 
Pre-Processor
First pass - parsing of pre-processed code, organising into tree, static type checking
Optional global optimiser
second pass - parsed tree generated into assembly language or machine code called .o files.
                  - optional peephole optimiser to check redundancy
linker
                  - references resolution, libraries linking
                  - all .o are combined together to make .exe which can be run on the OS 

--------------------------------------------------------------------------------------------------------------

References, pointers, Const, type conversions, variable types:

Q. What is the difference between char * const a; char const *b; and char *c;
A. char * const a -> a is a const pointer to a char : value can be changed but not the ptr
    char const *b -> b is a pointer to a constant char : ptr can be changed, but not the value
    char * c -> c is a pointer to a char : both can be changed

Q. What is mutable?
A. From a const member function, a mutable member variable can still be modified.

Mutable members of a const class instances are modifiable (from interview point of view), but this is hardly a good usage of mutable. It applies to non static class member of non reference non const type and specifies that the member does not affect the externally visible state of the class (mostly used in mutexes).

Q. What is volatile?
A. The keyword suggest the compiler to skip the object/variable marked as volatile to be omitted from optimisation, because the value can be changed by the code outside the scope of the current code. The code outside the current code can be - interrupt service routine that can modify the global variables, or global variables that can be modified/used by a different thread.

Q. Explain in plain simple English without using the word point/pointer – what is a pointer?
A. Its a memory location (variable) that is storing address of another memory location.

Q. What is volatile? Register? Auto? static? Extern? Mutable?
A. Volatile - see above - used in ISR and threading.
Register - It is a hint to the compiler to store the variable in a processor register instead of memory (stack, heap). The compiler may or may not be able to agree.
Auto - Different meaning after c++11.
Static - 
  Member variable : No matter how many objects you create, static member variable will be shared across them. All static data is initialised to zero when the object is created for the first time.
  Member function : Can be called without object. Can work only on static member variables. Can only call the member functions which are static. Doesn't have this pointer. Cannot be virtual.
  Static class : A class with all data variables and members inside it defined as static is a static class.
Extern - An info to the compiler that the variable exist somewhere not in the current file.
Mutable - See above, used correctly in multithreaded programs, wrongly used sometimes to change class members from const objects or const member functions.

Q. What are const_cast, static_cast, dynamic_cast, re-interpret_cast?
A. 
const_cast : To remove/bring in const ness and volatile ness in a variable/object. The types must be same. Can work on objects, ref and pointers.
static_cast : Non polymorphic cast, like casting a base class pointer into a derived class. Down n up cast. Will work only on related types. Can work on objects, ref and pointers.
dynamic_cast : Polymorphic cast. Typically used in down casting. Only works on ref and pointers. The 2 types must be polymorphic (have virtual functions). If fail, returns null (run time checks performed).
reinterpret_cast : Powerful and so dangerous. Can cast any type to any other type, even non related. only on pointers/references.

Q. What is typeid?
A. typeid(object).name would return the type_info object. Check the example - 
Class obj1, obj2; 
cout<
may print Class or CGlass or 9Class, which are internal names given by compiler to the class. But obviously, for both types, it would be the same, so they can be compared for equality.
It's mostly used on pointers to know the run time type of the pointer object. Defined in typeinfo header.

Q. What is the mechanism in passing by pointer, reference and value? Which is better in what scenario?
A. Mechanism : Passing by value - a new object needs to be instantiated (copy constr is invoked).
Passing by pointer - a new pointer memory will be needed, but no object instantiation.
Passing by ref - No new memory location needed, just a new alias of the existing object. 

If you pass by value, copy constr will be invoked, so not very efficient.
If you pass by pointer, a new pointer memory is needed.
If you pass by const ref, neither of the above is needed. Most efficient.


Q. What is object slicing? How do we get rid of this?
A. You have a Base class and a Derived class. And you have bObj and dObj.
Technically, you can type cast Derived class object into base class.
bObj = dObj;
When you do above, the specialities of Derived classes will be all sliced off.

It can be avoided by - 
1. Making base class as abstract, so no obj can be created at all.
2. Using pointers/references instead of objects.

--------------------------------------------------------------------------------------------------------------
C++ Design questions - 
Design a logger class structure.
Design a class hierarchy for elevators in the building.
Design a class hierarchy for traffic signal.

----------------------------------------------------------------------------------


Inheritance:
Q. What is inheritance (is-a) and composition (has-a)?
A. When you create object (mostly private) of an existing class inside your class (like std::string in MyClass), its composition.

Composition is generally used when you want the features of an existing class inside your new class, but not its interface. 
Inheritance, when you want to narrow down on the specifics of the class, with its interface.

Base class Land, derived can be garden, farm, lawn, desert, mountain etc.
Garden is a land, farm is a land, lawn is a land.

Member object soil, sand, rock etc can be part of some types of land.
Garden has soil, desert has sand, mountain has rock.

Side note : Constructor initialisation list - same syntax for base class data members, as well as composition object data members. Comma separated. This way, constructor for member objects are all called (and there's no other way).

Also, constructors are called in the sequence of object (s) declaration, not the object instantiation via constructor initialisation list.

Another side note : is-like-a relationship : When your derived class has methods that are not in base class, the relationship is 'is-like-a';

Q. When do we derive privately? Any real life example.
You can inherit a base class privately by leaving off the public in the base-class list, or by explicitly saying private (probably a better policy because it is clear to the user that you mean it). When you inherit privately, you’re “implementing in terms of;” that is, you’re creating a new class that has all of the data and functionality of the base class, but that functionality is hidden, so it’s only part of the underlying implementation. The class user has no access to the underlying functionality, and an object cannot be treated as a instance of the base class.

You may wonder what the purpose of private inheritance is, because the alternative of using composition to create a private object in the new class seems more appropriate. private inheritance is included in the language for completeness, but if for no other reason than to reduce confusion, you’ll usually want to use composition rather than private inheritance. However, there may occasionally be situations where you want to produce part of the same interface as the base class and disallow the treatment of the object as if it were a base-class object. private inheritance provides this ability.

Private Inheritance is one of the ways of implementing the has-a relationship

  1. "Private inheritance is most likely to be a legitimate design strategy when you're dealing with two classes not related by is-a where one either needs access to the protected members of another or needs to redefine one or more its virtual functions." 
  2. "Private inheritance means is-implemented-in-terms-of. It's usually inferior to composition"
  3. "If you make a class D privately inherit from a class B, you do so because you are interested in taking advantage of some of the features available in class B, not because there is any conceptual relationship between objects of types B and D."
  4. "Private inheritance means nothing during software design, only during software implementation."
Q. After private inheritance, how can you make members of base class public again?
A. The using directive. Just say 'using Base::Base_func or Base_data' in the public section of the derived class.

Q. What is the classic diamond inheritance problem?
A. The "diamond problem" (sometimes referred to as the "deadly diamond of death"[5]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

Q. What is the solution to classic diamond inheritance problem?
A. C++ fixes the diamond inheritance problem by virtually inheriting the mid level classes (B,C) from the base most class (A).
Java did not support multiple inheritance before Java 8. Post java 8, it fixes the problem by raising a compile error.

Q. What types of inheritance exist?
Public inheritance
Public remains public, protected remains protected, private doesn't get inherited at all.

Protected inheritance
Public become protected, protected remains protected, private doesn't get inherited at all.

Private Inheritance 

Public become private, protected becomes private, private doesn't get inherited at all.

Q. What are problems with multiple inheritances? (Multiple, not multilevel)
ToDo (TICPP - Vol2)

Q. What is upcasting? 
Doing Base *B = Derived &d (via function calls etc) is called upcasting, and its safe.
-----------------------------------------------------------------------------------------------------

Operator overloading:

Q. Which operators can not be overloaded and why?
A. 
  • The . Member selection operator; The tertiary operator ?: ; The :: scope resolution; and The .* pointer referencing in object operator.
  • The member selection operator.. Currently, the dot has a meaning for any member in a class, but if you allow it to be overloaded, then you couldn’t access members in the normal way; instead you’d have to use a pointer and the arrow operator->.
  • The pointer to member dereference operator.*, for the same reason as operator..
  • There’s no exponentiation operator. The most popular choice for this was operator** from Fortran, but this raised difficult parsing questions. Also, C has no exponentiation operator, so C++ didn’t seem to need one either because you can always perform a function call. An exponentiation operator would add a convenient notation, but no new language functionality to account for the added complexity of the compiler.
  • There are no user-defined operators. That is, you can’t make up new operators that aren’t currently in the set. Part of the problem is how to determine precedence, and part of the problem is an insufficient need to account for the necessary trouble.
  • You can’t change the precedence rules. They’re hard enough to remember as it is without letting people play with them.

Q. Which operators are special wrt overloading and why?
A. 
1. prefix and postfix ++ and -- : We have to overload postfix with an additional int param, which is never passed, but here to make a differentiation between prefix and postfix.
2. () is special because its widely used.
3. = same as 2.

Q. Which operator overloading has to be member functions and why?
A. = ( ) [ ] –> –>* : Because, if you overload them as global, then before its definition, the default meaning will be taken, and after the definition the overloaded meaning will be taken; which will result in weird behaviour.

Following are recommended to be members, but not mandatory - 
+= –= /= *= ^=  &= |= %= >>= <<=, and all unary operators.

Q. Which operators need friend to be overloaded and why?
A. https://www.quora.com/Why-do-we-need-friend-functions-What-is-their-use-in-operator-overloading-Can-the-member-functions-of-object-not-do-the-same-thing

Q. Signature of operator overloading for a given operator.
A. MyClass & operator() {}

--------------------------------------------------------------------------------------------------------------

Copy constructor and assignment operator overloading:
Copy constructor syntax : X (X&), without any return value

Q. When is copy constructor called?
A. When you pass an object by value, return by value or try to instantiate an object from an existing object : X x = y; copy constructor is invoked. If you don't define your copy constructor, compiler provides one, which does a bit by bit copy (shallow copy).

Q. When is copy constructor needed?
A. The moment you have something in your class (like a pointer, memory for which is allocated on heap), that when done bit by bit copy, doesn't give the desired results during pass by value, return by value or new object instantiation, a copy constructor is your answer.

A private copy constructor is needed if you want to avoid passing by value for that class's object.

Q. Why do we pass by const ref?
A. When we have following 2 conditions to be met - 
    a. Efficiency of passing by reference
    b. The called function should not attempt to modify the ref value.

rvalue from C++ is a must read concept.

Q. What does copy constructor return?
A. Nothing.


Q. When is assignment operator called?
A. When an existing object is being assigned to another existing object. Obj a, b; a=b;


Q. Can 'operator=' overloaded function be a non member? Why?
A. Note that 'operator=' is only allowed to be a member function.
If you create a global/standalone 'operator=', the semantics of copy-assignment would change in the middle of the translation unit - before the declaration of this overload, the compiler's version will be used. After the declaration, the custom definition will be used. The behaviour of the program will depend on where the global copy-assignment is declared. This is considered unacceptably dangerous.

Same with these operators - (), [],->, ->*

Full details here - https://stackoverflow.com/questions/3933637/why-cannot-a-non-member-function-be-used-for-overloading-the-assignment-operator

Q. When is assignment operator overloading needed?
A. Same reasons as the need for a copy constructor.


Q. Signature of overload function of assignment operator.
A. Class & operator=(const Class &rhs){}
Note : operator=() doesn't get inherited, because it has a constructor like purpose, specific to the class.

Q. Why do we return by ref?
A. Same reasons as passing by ref or const ref.

Q. What is the problem with self assignment? Why do we have to check for self assignment in operator= overload?
A. ToDo.

Q. What is the difference at implementation level between copy constructor and overloaded assignment?
A. ToDo

Also, 
You could replace copy construction by default construction plus assignment, but that would be less efficient. 


Q. What is shallow copy and deep copy?
A. Detailed classic answer.
With C++11, move constructor (and rvalues) is used for shallow copy; whereas copy constructor is used for deep copy.

--------------------------------------------------------------------------------------------------------------
----------------------------


Class:
Q. What is an explicit constructor? What do we achieve by having an explicit constructor?
A. By using explicit keyword with a constructor, we are preventing implicit conversions and copy-initialisation.
Trivial example - With the explicit keyword, we can prevent constructing a string object from char array or a char pointer.

A constructor without the explicit keyword is called a converting constructor, because it converts the passed parameter to the class type.

Q. What is copy-initialisation?
A. Its initialising of an object from another object, which can happen in following scenarios - 
1) when a named variable (automatic, static, or thread-local) of a non-reference type T is declared with the initialiser consisting of an equals sign followed by an expression.
2) (until C++11)when a named variable of a scalar type T is declared with the initialiser consisting of an equals sign followed by a brace-enclosed expression (Note: as of C++11, this is classified as list initialisation, and narrowing conversion is not allowed).
3) when passing an argument to a function by value
4) when returning from a function that returns by value
5) when throwing or catching an exception by value
6) as part of aggregate initialisation, to initialise each element for which an initialiser is provided

Q. What functions are provided by compiler by default? Are they private or public
A. They are public by default.
C++98/03, if needed - 
the compiler will generate a default constructor for you unless you declare any constructor of your own.
the compiler will generate a copy constructor for you unless you declare your own.
the compiler will generate a copy assignment operator for you unless you declare your own.
the compiler will generate a destructor for you unless you declare your own.
As Péter said in a helpful comment, all those are only generated by the compiler when they are needed. (The difference is that, when the compiler cannot create them, that's Ok as long as they aren't used.)
C++11
C++11 adds the following rules, which are also true for C++14 (credits to towi, see this comment):
The compiler generates the move constructor if
there is no user-declared copy constructor, and
there is no user-declared copy assignment operator, and
there is no user-declared move assignment operator and
there is no user-declared destructor
it is not marked as deleted,
and all members and bases are moveable.
Similar for the move assignment operator: It is generated if there is no user defined
there is no user-declared copy constructor, and
there is no user-declared copy assignment operator, and
there is no user-declared move constructor and
there is no user-declared destructor,
it is not marked as deleted,
and all members and bases are moveable.
Note that these rules are a bit more elaborated than the C++03 rules and make more sense in practice.

Q. Why do we have protected keyword?
A. When we have something (a function mostly) which we don't want to be accessible by an object, but want to be inherited by the derived classes.

Q. What is a pure virtual function? What is an abstract class? Why can’t we create an object of an abstract class?
A. A member function in the class with a virtual keyword (often times without a definition, but can have a definition) and having '= 0;' in its declaration, is a pure virtual function. All classes derived from this class must define (override) the pure virtual function. If a class doesn't do it, it become an abstract class.
Any class with a pure virtual function is an abstract class, which can not be instantiated at all. 
It can not be instantiated because ---- ToDo for me, to figure out when we say a virtual void func() = 0; does it mean the function pointer in the vtable points to 0 (null) and that's the technical reason why we can not create an object of abstract base class.

Its set by C++ standards to not let the abstract base class be instantiated because its not defined. Imagine to be asked to draw(create an object of) a vehicle (base class), what would you create? A car, a bike or a space ship? 


Q. Is it okay to have static member functions in an abstract class?
A. There's nothing special about this. You would invoke the static function in an abstract class just like static function in a non-abstract class - without an object. The static function will not have this pointer, and static function cannot work on the class members because of lack of object. However, you can pass an object and the static function can work on that passed object.

Q. Why do we need an abstract class? What rule it applies on the derived classes?
A. A member function in the class with a virtual keyword (often times without a definition, but can have a definition) and having '= 0;' in its declaration, is a pure virtual function. Such class is an abstract class. All classes derived from this class must define (override) the pure virtual function. If a class doesn't do it, it become an abstract class.

Q. What is delayed construction?


Q. What is converting constructor?

A constructor without the explicit keyword is called a converting constructor, because it converts the passed parameter to the class type.

Q. What is lazy construction?
A. See the C++ 11 interview questions page.

Q. What are inline functions? When a function does/doesn’t become inline?
A. When a normal function call instruction is encountered, the program stores the memory address of the instructions immediately following the function call statement, loads the function being called into the memory, copies argument values, jumps to the memory location of the called function, executes the function codes, stores the return value of the function, and then jumps back to the address of the instruction that was saved just before executing the called function. Too much run time overhead.

'Inline' keyword is a request to the compiler to replace the function call by the function code itself (expansion), during pre-compile time, and then proceeds with compilation.

All the member function declared and defined within class are Inline by default. So no need to define explicitly.

When making inline functions, care needs to be taken of the following aspects - 
1. It increases the executable size due to code expansion. 
2. C++ inlining is resolved at compile time. Which means if you change the code of the inlined function, you would need to recompile all the code using it to make sure it will be updated
3. When used in a header, it makes your header file larger with information which users don’t care.
4. As mentioned above it increases the executable size, which may cause thrashing in memory. More number of page fault bringing down your program performance.
5. Sometimes not useful for example in embedded system where large executable size is not preferred at all due to memory constraints.

Its implementation dependent, but mostly, Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in function body.
5) If a function contains switch or goto statement.

Q. What are namespaces? How is it resolved by C++?
A. Namespaces are organisation unit that can contain classes, methods, etc. Namespace can be split over multiple files.

When you say using namespace std, you do not have to use 'std::' to call cout.
However, if you only include the class (iostream), you can access like - 'std::cout'.

'using' is a C++ directive - used to bring all namespace members into current scope. This is called u'using directive'.
You can also bring a specific member like - 'using std::cout'. This is called 'using declaration'.

ToDo - How is namespace resolved during compile time?
Koenig lookup or Argument Dependent Lookup (ADL)


Q. What is anonymous namespace?
Namespace without a name. Methods, variables defined in an anonymous namespace are only accessible in the same file.

Q. What is name hiding?
A. Anytime you redefine an overloaded function name from the base class, all the other versions are automatically hidden in the new class.
Base class has void f(int a), Derived has void f(). You have a derived object, and try to call derivedObj.f(8); the code will not compile. This is called name hiding. There's no function overloading here.
Name hiding can be fixed by doing 'using Base::f' in derived class.

Q. What is name mangling?
Name mangling is the encoding of function and variable names into uniquenames so that linkers can separate common namesin the language. Type names may also be mangled. 

Myclass::func(int a) const - after name mangling could be - _func_Ar£

Q. Sizes of different primitive data types?
A. Mostly hardware/compiler dependent; but generally - 
Int .     4 bytes (short int - 2, unsigned int - 4, long int 8)
Char .   1 byte
Bool
Float    4 bytes
Double 8 bytes . (long double - 16 bytes)
Any ptr - size of int - 4 bytes

Q. What is a union? Enum?
A. Union is just here to support migration from C to C++. Do not use anywhere else.
A union with say, an int and a char; only one can be used at a time.

Enum - enumerated values. enum Color = {black = 0, blue, yellow}, will set black to be 0, blue to be 1 an yellow to be 2 respectively. Mostly used in field type definitions.

Q. What is difference between struct and class?
A. Only one difference - private in class, Vs public in struct. More differences with C++11, 14 etc.

Q. Can my class inherit from a struct?
A. yes, same result as inheriting from a class, with an exception that members of struct are public by default.

Q. How can you prevent a class from being inherited?
A. Making constructor private. Or using the C++ final keyword.

Q. How can you make sure no objects on stack are permitted?
A. By making destructor private - compiler is responsible to call destructor on the stack objects, but since destructor is private, it will throw an error.
Compiler is not responsible to call destructor for heap objects, so heap objects can still be created. We will need a new function say 'destoryer' which will call destructor (or not).

Q. How can you make sure no objects on heap permitted?
A. Overload operator 'new' privately in your class, so whenever you try to do Myclass *obj = new Myclass, it will fail.

--------------------------------------------------------------------------------------------------------------

Memory :

Q. What is a memory leak?
A. A memory location on free store (new/delete) or heap (malloc/free) which doesn't have any pointer referencing to it, is a leaked memory.

Q. Under what scenarios in C++ can a memory leak happen?
A. Memory is allocated on heap, using new/malloc/realloc/calloc, but not deallocated, and the pointer pointing to that memory has lost the address. Now there's no way to reach that memory location. Scenarios like this cause memory leaks.

Q. Ways to prevent memory leak?
A. Always make sure to delete/free the dynamic allocated memory.
     Take care for data structures and containers, so that memory for all the elements is freed.
     Use of advanced features is almost always good - shared ptr, auto_ptr, smart_ptr, unique_ptr.

Q. Do you know smart pointers – std::auto_ptr, boost::shared_ptr?
A. No short answer.

Q. Do you know ref counting smart pointer implementation?
A. A good n easy implementation here - https://www.codeproject.com/Articles/15351/Implementing-a-simple-smart-pointer-in-c
Due credit to Madhu Raykar, the author of above page.

Q. Can we call smart pointer as C++’s way of garbage collection?
A. Yes. Many products have their libraries for memory management. The intent is not let every programmer use new and delete (and probably raise chance of errors).
All classes have to be derived from a memory managed base class, with virtual destructor.

Q. What are different memory segments for a process?
A. Following areas -
Code-Code (text instructions)
Statics-Static data and global data
Heap-Free store - location for dynamic memory allocation
Stack-function / program stack

Q. What is segmentatoin fault? What is Bus error? What is the difference between the two?
A. Segmentation fault :
The following are some typical causes of a segmentation fault:
  • Attempting to access a nonexistent memory address (outside process's address space)
  • Attempting to access memory the program does not have rights to (such as kernel structures in process context)
  • Attempting to write read-only memory (such as code segment)
These in turn are often caused by programming errors that result in invalid memory access:
  • Dereferencing a null pointer, which usually points to an address that's not part of the process's address space
  • Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address)
  • Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted)
  • buffer overflow or a stack overflow.
Bus Error : Very rare these days, but can still happen
Caused by trying to access non existent address, unaligned access or paging errors or non present segments.

--------------------------------------------------------------------------------------------------------------

Virtual mechanism:

Q. What is a virtual destructor? Why do we need it?
A. When there is inheritance and polymorphism involved, with dynamic memory allocation in the derived class (or some code which makes derived class destructor calling critical), and we have a base class pointer pointing to a derived class object, a virtual destructor in the base class ensures derived class destructor called before calling the base class, so the object is properly, completely and sequentially destroyed in the way it was constructed.

Q. Can we have a virtual constructor?
A. It doesn't make any sense, because anyways the base class constructor is called first followed by the derived class. Also, for virtual mechanism to work, we do not have enough information at construction time. So, no point.

Q. What is the concept behind virtual mechanism?
A. This is implementation dependent, and not defined in C++ spec.
However, almost all C++ compilers use virtual tables and function pointers to implement virtual mechanism. If you have a class with atleast one virtual method, the compiler will add a hidden pointer to the vtable. Each constructor will then set this hidden pointer to the virtual table of the class it belongs to.
The example here may be useful - https://en.wikipedia.org/wiki/Virtual_method_table

Q. What constitutes a signature of the function, which gets considered for virtual mechanism?
A. Part of signature - Function name, parameters, constness.
     Not part - return type.
     What about the 'throw' keyword in function signature? Do it yourself.


Q. How many vtable does my class/obj have?
A. A vtable for base class, and one vtable each for all derived classes from the base. This is resolved at compile time.

Q. How many vptr does my class/obj have?
A. Each object has a vptr. Typically first 4 bytes of the object memory space is reserved for the vptr, whenever there's virtual mechanism involved. This vptr points to the appropriate vtable for that object type. This is resolved at runtime.

Good explanation here - https://www.youtube.com/watch?v=Eaz0P_gJ9FE

Q. What is function over-riding? How is it different from function overloading?
A. Run time polymorphism is function over-riding. C++11 has the override keyword for it.
Compile time function polymorphism is function overloading.
----------------------------------------------------------------------------------------------------------------------

Exceptions:
Q. Can we throw exceptions from constructor? Is it safe? When do we do it?
A. Yes we can.
Safe - Yes. If c'tor throws, it means the object was not constructed fully. So, d'tor will not be called. When inheritance is involved, (assuming we have virtual d'tor) if Base class c'tor throws, no d'tor will be called. If Derived class d'tor throws, base class d'tor will be called, because its c'tor did complete. However the inheritance bit needs to be verified by running some trial programs. ToDo for myself.
When do we do it? - You should throw an exception from a constructor whenever you cannot properly initialise (construct) an object. There is no really satisfactory alternative to exiting a constructor by a throw.

Q. Can we throw exceptions from destructor? Is it safe? When do we do it?
A. Yes we can.
Safe - No. You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by a throw, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated. Don't do it.
TICPP - terminate() is called if destructor of a local object throws an exception during stack unwinding.

Q. What happens if you throw an exception of type b, but there is no catch for it?
A. If you throw an exception, all functions will be exited back to the point where it finds a try...catchblock with a matching catch type. If your function isn't called from within a try block, the program will exit with an unhandled exception.

Q. What do you mean by exception safety of the code?
A. By exception safety, it means, the code is still safe and exhibits well defined behaviour in case of exception. There are multiple levels of exception safety -
No Throw Guarantee : Everything is handled within the function (relevant catch blocks for all types of exception that can be thrown from that function)
Strong exception safety : Commit or Rollback semantics - operations can fail, but it will be clean functional failure without any side effects.
Basic exception safety : Resource (Memory) leaks are taken care of; but may not be clean functional failure.
No exception safety : No guarantees are made. Extremely dangerous.

Q. What happens when you throw an exception?What is stack unwinding?
A. When you throw an exception, it will go up the stack until it finds an exception handler of the matching type. If it can't find, the program will exit with an unhandled exception. If it does, it will rewind the stack up to that point, and continue with the code from the handler block, wherever it is.

When the scope is exited, everything within that scope is destroyed by calling their destructors. This process of destroying local objects and calling their destructors is called stack unwinding.
Special care to be taken wrt stack unwinding -
1. Dynamic memory will not be freed.
2. No destructors (which are called during stack unwinding) to throw exceptions which are not being caught within that destructor. This will result in undefined behaviour (terminate unexpectedly).

Q. When is unexpected() called?
A. If you throw an exception which is not listed in your exception specification, this function is called. The default unexpected() calls terminate(). The default terminate() calls std C lib abort(). When abort() is called, no calls to normal program termination functions occur, which means destructors for global/local objects are called.
We can define our own unexpected_handler by using set_unexpected.

Q. When is terminate() called?
A. Its called when throw can't find a matching catch handler, or when its impossible to continue the exception handling process.
We can define our own terminate_handler by using set_terminate.

----------------------------------------------------------------------------------------------------------------------

New and delete:

Q. What care to be taken when doing 'delete this'? What happens when you say delete this from a member function?
A. If following care is taken, its perfectly fine to do delete this from a member function. Its immensely risky to take so much care.

  • You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
  • You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.
  • You must be absolutely 100% positively sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
  • You must be absolutely 100% positively sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.
Copied from here - https://stackoverflow.com/questions/7039597/what-will-happen-if-you-do-delete-this-in-a-member-function
All credit goes to Alok Save, the original answerer.

Q. What happens when you say delete this from a constructor?
Delete this is fine; but if we are trying to access fields after delete this, we will encounter heap corruption. Also, why do delete this? The destructor will get called and weird things may happen, if destructor accesses this.
I would rather do a throw from constructor instead of delete this, and handle the object deletion there. When you throw, the destructor will not get called anyways, so it can be made safer to do this way.
ToDo for me to examine by running the code myself.


Q. What happens when you say delete this from a destructor?
A. Safer than calling delete this from the constructor; just ensure - 
The object was allocated by new, the object is not used later (for pointer comparison, accessing data and functions).

Q. What happens when delete gets called?
A. Destructor is called for user defined types.
Memory is released back to the memory manager.
Your pointer is still a valid pointer, after delete, just that there's no guarantee that the memory it points to is valid.

Q. What are different ways to use delete?
A. delete pointer, delete array[], operator overloading of delete.

Q. Can you do a delete ptr, where ptr is not dynamically allocated, or ptr is null, or uninitialised?
A. If the ptr is not allocated using new, delete'ing it will result in undefined behaviour. Also destructor will be called on the memory location pointed to by ptr, for the ptr data type, which will further result in undefined behaviour.

Q. What is the diff between new and malloc? Free and delete.
A. The malloc and free are functions in C library.
New and delete are C++ operators. (so they are relatively faster)
New and delete will invoke constructors and destructor respectively.
New and delete can be worked on arrays (using [])

Q. What does it mean by : p = new (nothrow) int[i]; ? 
A. Meaning, if there's a memory allocation error, it will not throw 'bad_alloc', rather return nullptr pointer, and 'std::bad_alloc' will be output to the standard output.

Q. What is a placement new?
A. This can be used to re-construct the preallocated object. As it allows to construct an object on memory that is already allocated , it is required for optimizations as it is faster not to re-allocate all the time. There may be cases when it is required to re-construct an object multiple times so, placement new operator might be more efficient in these cases.

Q. How does delete[] know how many elements to be deleted?
A. Its arranged in memory as:
[info][memory you asked for...]
Where info is the structure used by your compiler to store the amount of memory allocated, and what not.
This is implementation dependent though, and not defined in C++ spec.
----Credit goes to answer by Francisco Soto on stack overflow here -
More details here - https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array

-------------------------------------------------------------------------------------------------------------
Miscellaneous:Write code for recursive function for palindrome?
Write code for non-recursive function for palindrome?
Write code for function to delete an element from a queue/link list?
Write code for finding out the least common ancestor from a tree?
Write code for pre/post/in order searching/traversing in a tree?
Write a code for template function for *****? (I don’t remember the purpose)
Write code to reverse a sentence wordwise, but words are not to be reversed.
(Hello World becomes World Hello) Use standard libraries and containers etc.

-------------------------------------------------------------------------------------------------------------------------

Design patterns:Singleton
Can we make constructor as protected?
Have you ever seen any usage of making it protected?
What happens if we make any of the following public –
Destructor, constructor, copy constructor, assignment operator?

Bridge
Factory method (Virtual constructor)
Abstract Factory
Observer
Template method
Façade

-------------------------------------------------------------------------------------------------------------------------

Multithreading:Multi-threaded singleton
A typical queue example – which uses semaphores and locks both.
How do we take thread dump?
Which debugger have you used for threaded code?
The typical lock class.
Problems with multithreading – race condition, deadlock.
Difference between threads and processes?
What is a thread pool?
What is context switching for a thread?

-------------------------------------------------------------------------------------------------------------------------

STL:Which one to use when? Especially between – list, vector and maps?
Time complexity for find operations for all containers.
Ways of efficient use of STL containers.
Why is iter++ less efficient than ++iter?
What is the problem using templates? Does it make code a bit slower?
Time complexity of sorted array, sorted list?
Generally, on a broad level, when do iterators get invalidated?
Can smart pointer (auto_ptr) work with arrays?

-------------------------------------------------------------------------------------------------------------------------

Boost:More about shared_ptr, weak_ptr and associated classes.

IPC:What are different IPC mechanisms provided?
Have you heard of signals?
Which signals cannot be caught?
Which IPC is to be used under what scenarios?
What are sockets?
Types of sockets?
Which one to use when?
Typical socket operations from client and server side.

-------------------------------------------------------------------------------------------------------------------------

Database:What is a primary, unique, foreign, composite key?
What are joins. Equi, non equi, self, inner, outer joins?
How do we tune a query?
How to take table dump into a file?
Query to retrieve duplicate rows?
Query to retrieve row for top 2nd salary?
What is a rowid and row_number?
Is Sybase more efficient than Oracle?
What are triggers?
What is a stored proc?
How do we pass variables to a stored proc?
What is a transaction log on Sybase?
Indexes : Pros and cons?
What are commands for import/export and/or bcp in/out?
What are the various types of constraints?
What is referential integrity?
What are normalisation forms? And what are they used for?
What is the command to see if a particular query has used index or not?

-------------------------------------------------------------------------------------------------------------------------

UNIX:Details of following commands -
Find, grep, tail, ps, netstat, sed, awk, ls, touch, cat, <<, >>, vi
A command to list only the directories?
A command to find files modified/created in the last 5 days?
The piping of commands together.
UNIX scheduler – crontab
Is Linux better than UNIX? Why?
What is make? How does it work?
What c, c++ compilers have you used?

-------------------------------------------------------------------------------------------------------------------------

Shell scripting:What is the first line in a typical shell script?
Can you have functions in a shell script?
How do you pass variable to a shell script?
How do you define an array, if at all?
Where does shell execution begin? If the script has multiple functions, how does the execution begin?
What is ‘export’ command?

Which all shells are available today?