C/C++ Language Fundamentals Flashcards
What is the difference between malloc and new in C/C++?
malloc allocates raw memory in C, doesn’t call constructors, and returns void*. new is C++-specific, allocates memory, calls constructors, and returns typed pointer. malloc requires manual size calculation; new handles it automatically.
What is a dangling pointer?
A pointer that references memory that has been deallocated (e.g., after free or delete), leading to undefined behavior if dereferenced.
Explain the difference between const and constexpr in C++.
const ensures a variable’s value doesn’t change after initialization; evaluated at runtime. constexpr ensures compile-time evaluation, used for constants and functions to optimize performance.
What is the purpose of a virtual function in C++?
A virtual function enables runtime polymorphism, allowing derived classes to override base class methods. Declared with virtual keyword; requires vtable for dynamic dispatch.
What is RAII in C++?
Resource Acquisition Is Initialization: resources (e.g., memory, files) are acquired in a constructor and released in a destructor, ensuring automatic cleanup (e.g., std::unique_ptr).
What is the difference between a pointer and a reference in C++?
A pointer is a variable storing a memory address, can be reassigned, and may be null. A reference is an alias for a variable, cannot be reassigned, and cannot be null.
What is the volatile keyword used for in C/C++?
Tells the compiler not to optimize access to a variable, as its value may change unexpectedly (e.g., hardware registers or multithreaded variables).