Interview problems on C++

1. Difference between pointer and reference:
A pointer is a variable storing the memory address of the variable it points to. It is safe to think of a reference as an alias of the variable.
(1) A pointer should be dereferenced with * while a reference can be used directly.
(2) A pointer can be reassigned while a reference cannot once initialized.
(3) A pointer can be assigned to point to nullptr directly while a reference cannot.
(4) We can perform arithmetic operations on a pointer.
(5) Pointer of pointer provides multiple levels of indirections.

2. Inheritance: 'is a'

3. Virtual:
(1) A virtual function is a member function that is declared in the base class with keyword 'virtual' and can be overridden by derived classes.
(2) A pure virtual function is a virtual function without implementation in the base class. It is specified by '=0' in the declaration.
(3) A abstract class is a class that contains at least one pure virtual function.
(4) An interface is a class with only pure virtual functions and no data members.

4. (Runtime) polymorphism:

const Base& base = Derived(…) or Base* ptr = &derived


5. Vtable and vpointer:
For each class that contains virtual functions, the compiler creates a vtable which contains the addresses of all virtual functions in this class.
For each instances of that class, the compiler adds a vpointer that points to the vtable for that class. The vpointer will be used to call the actual function from the vtable at runtime.

6. Because of the runtime binding, the constructor of a class can NOT be virtual. Because of the runtime polymorphism, the destructor of a base class has to be virtual.

7. When to define copy constructor?
Rule of three (five): if a class define one or more of the following, it should explicitly define all three (five): destructor, copy constructor, copy assignment operator (move constructor, move assignment operator).

8. Memory leaks for smart pointer?
Cyclic references.
  

Comments

Popular posts from this blog

529 Plan

How to offset W2 tax

Retirement Accounts