C++ Interview Questions and Answers: Core Language Concepts and Best Practices
This comprehensive guide covers 40 common C++ interview topics, including procedural vs. object‑oriented programming, differences between C and C++, static and const keywords, pointer versus reference semantics, memory allocation with malloc/new, function overloading, inheritance, virtual functions, templates, smart pointers, and modern C++11 features, providing clear explanations and example code.
Welcome to the C++ interview session! The following questions test your understanding of C++ fundamentals, object‑oriented programming, templates, STL, and related concepts.
1. Difference between procedural and object‑oriented programming
Procedural programming focuses on functions and step‑by‑step algorithms, keeping data separate from functions, while OOP encapsulates data and behavior within objects, emphasizing abstraction, inheritance, and polymorphism.
Procedural: algorithm‑centric, data separate.
OOP: object‑centric, data and methods together.
Inheritance and polymorphism are core to OOP, absent in procedural code.
Code reuse: procedural uses modular functions; OOP uses class hierarchies and composition.
Choice depends on project size, team, and maintainability requirements.
2. Difference between C and C++
C++ supports classes, inheritance, and polymorphism; C does not.
C++ offers richer standard library, templates, and exception handling.
C standard library provides basic I/O and string functions; C++ adds containers and algorithms.
Exception handling is native to C++; C uses error codes.
C++ compilers can compile C code, but C compilers may not understand C++ syntax.
3. Role of the static keyword
Static local variables retain their value between function calls. Static functions have internal linkage, limiting visibility to the translation unit. Static global variables are limited to the file scope, preventing name clashes. Static class members belong to the class itself.
void increment() {
static int counter = 0;
++counter;
std::cout << "Counter: " << counter << std::endl;
}
int main() {
increment(); // Counter: 1
increment(); // Counter: 2
increment(); // Counter: 3
return 0;
}4. Role of the const keyword
Used to declare immutable variables, protect function parameters, mark member functions as non‑modifying, and define read‑only return values.
const int MAX_VALUE = 100; void printMessage(const std::string& message) {
std::cout << message << std::endl;
} class MyClass {
public:
void printValue() const { std::cout << value << std::endl; }
private:
int value;
};5. synchronized vs. volatile
C++ has no direct synchronized keyword; mutexes provide similar mutual‑exclusion. volatile tells the compiler not to optimize accesses, useful for hardware registers or signal handlers, but it does not guarantee atomicity or memory ordering.
6. Difference between struct and union in C struct allocates separate memory for each member; union shares a single memory region among all members, allowing only one active member at a time.
7. Difference between struct and class in C++
Default access: struct members are public; class members are private. Otherwise, they are functionally equivalent.
8. Array vs. pointer
Arrays have fixed size and static allocation; pointers can be reassigned and point to dynamically allocated memory. Array names decay to pointers when passed to functions.
9. Program execution process
Compilation to object code.
Linking external symbols.
Loading into memory.
CPU execution of instructions.
Runtime library calls.
Program termination and resource cleanup.
10. Pointer vs. reference
Pointers can be null, reassigned, and require dereferencing; references must be bound at initialization, cannot be null, and act as aliases.
11. malloc / free vs. new / delete
Allocation size specification and type safety.
Constructors are called with new, not with malloc.
Memory alignment guarantees differ.
12. ++i vs. i++
Pre‑increment returns the incremented value; post‑increment returns the original value before increment.
int i = 3;
int a = ++i; // a = 4, i = 4
int b = i++; // b = 4, i = 513. Pointer function vs. function pointer
Pointer function returns a pointer; function pointer stores the address of a function.
int* getPointer(); // pointer function
int (*funcPtr)(int, int) = add; // function pointer14. Pointer array vs. array pointer
Pointer array: array of pointers. Array pointer: pointer to an entire array.
int* ptrArr[5]; // pointer array
int (*arrPtr)[5] = &arr; // array pointer15. Pointer to const vs. const pointer
Pointer to const: cannot modify the pointed‑to value. Const pointer: cannot change the address stored.
const int* pConst; // pointer to const
int* const constPtr = &value; // const pointer16. Pass‑by‑value, pass‑by‑pointer, pass‑by‑reference
Value: copies data; safe but may be costly.
Pointer: allows modification via address; requires null checks.
Reference: alias to original; cannot be null.
17. extern "C"
Disables name mangling so C++ code can link with C functions.
18. Endianness
Big‑endian stores most‑significant byte first; little‑endian stores least‑significant byte first. Alignment padding may be added by compilers.
19. Deep copy, shallow copy, copy‑on‑write
Deep copy duplicates all referenced data; shallow copy copies only pointers; copy‑on‑write defers copying until modification.
20. Basic C++ data types
Integral types (bool, char, int, unsigned, short, long, etc.), floating‑point types (float, double), enumeration, and character arrays/strings.
21. Reference vs. pointer
Reference must be initialized and cannot be reseated.
Pointer can be null and reassigned.
References have no separate address; pointers do.
22. Function overloading
Same function name with different parameter lists; return type alone does not differentiate.
// overload examples
int add(int a, int b);
int add(int a, int b, int c);
float add(float a, float b);23. Class vs. object
Class is a blueprint; object is an instantiated entity with its own state.
24. Access specifiers
public: accessible everywhere.
protected: accessible in class and derived classes.
private: accessible only within the class.
25. Virtual vs. pure virtual functions
Virtual functions may have implementations; can be overridden.
Pure virtual functions have no implementation; make the class abstract.
26. Inheritance (single and multiple)
Single inheritance derives from one base class; multiple inheritance derives from several bases, potentially causing the diamond problem.
27. Destructor
Automatically called when an object’s lifetime ends to release resources.
class MyClass {
public:
~MyClass() { /* cleanup */ }
};28. Friend functions
Non‑member functions declared with friend can access a class’s private and protected members, useful for operator overloading.
29. Namespaces
Provide logical grouping, avoid name collisions, and improve code organization.
30. Templates
Enable generic programming; can define template classes and functions.
template <typename T>
class MyClass { T data; };
template <typename T>
T getMax(T a, T b) { return (a > b) ? a : b; }31. Common STL containers
vector, list, deque, stack, queue, priority_queue, map, set.
32. Exception handling
Use try / catch blocks; exceptions propagate up the call stack if not caught.
33. Operator overloading
Define custom behavior for operators by implementing member or non‑member functions.
Vector operator+(const Vector& other) const { return Vector(x+other.x, y+other.y); }34. Virtual inheritance
Solves the diamond problem by ensuring only one base‑class subobject exists.
class Mammal : public virtual Animal { };
class Bird : public virtual Animal { };
class Platypus : public Mammal, public Bird { };35. Conversion operators and explicit casts
Conversion operators enable implicit type conversion; explicit casts ( static_cast, dynamic_cast, reinterpret_cast, const_cast) provide controlled conversions.
36. Smart pointers std::unique_ptr: exclusive ownership. std::shared_ptr: shared ownership with reference counting. std::weak_ptr: non‑owning observer.
37. C++11 features
Lambda expressions, auto, range‑based for, nullptr, scoped enums, smart pointers, move semantics, initializer lists, static_assert, threading library.
38. Static vs. dynamic assertions
Static assertions are evaluated at compile time ( static_assert); dynamic assertions are runtime checks using assert.
39. Virtual destructors vs. non‑virtual constructors
Destructors can be virtual to ensure proper cleanup through base‑class pointers; constructors cannot be virtual because the object’s type is not yet fully formed.
40. const vs. #define const respects scope, type safety, and occupies storage. #define is a preprocessor textual substitution without type checking.
These topics collectively provide a solid foundation for C++ technical interviews and deepen understanding of language mechanics.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
