Ace your technical interview rounds. We break down the most frequent C++ questions on pointers, object-oriented concepts, STL, and memory management with detailed code examples and memory tracing.
Key C++ Interview Concept: Pointers vs. References
A **pointer** is a variable that stores the memory address of another variable, and it can be reassigned or set to NULL. A **reference** is an alias for an existing variable, cannot be reassigned, and must be initialized upon declaration.
C++ Memory Tracing Example
#include <iostream>
int main() {
int val = 42;
int* ptr = &val; // Pointer stores address of val
int& ref = val; // Reference is an alias for val
std::cout << "Value: " << val << "\n";
std::cout << "Pointer holds address: " << ptr << " pointing to value: " << *ptr << "\n";
std::cout << "Reference holds value: " << ref << "\n";
}
Step-by-Step Memory Explanation
- Suppose the integer variable
valis stored at memory address0x7ffd50containing value42. int* ptr = &val;allocates a new variableptrat address0x7ffd58. The value stored insideptris the literal address0x7ffd50.int& ref = val;does not allocate new memory. It is simply a compile-time alias. Any operation onrefis translated directly to operations on address0x7ffd50by the compiler.
What is a Virtual Function?
A **virtual function** in C++ is a member function in a base class that you expect to redefine in derived classes, enabling run-time polymorphism via a VTABLE lookup.
class Base {
public:
virtual void show() { std::cout << "Base class\n"; }
};
class Derived : public Base {
public:
void show() override { std::cout << "Derived class\n"; }
};
When a class declares a virtual function, the compiler inserts a hidden pointer (usually at the start of the object) called vptr which points to a static table of function pointers called **VTABLE**. At runtime, calling base_ptr->show() resolves to base_ptr->vptr->vtable[0](), dynamically calling the overridden function in Derived.