Basics of C++


Basics of C++ Interview with follow-up questions

1. What are the key features of C++?

C++ is a general-purpose, multi-paradigm programming language with a rich feature set that has grown substantially through C++11, C++14, C++17, C++20, and C++23. Key features interviewers expect you to know:

  1. Object-oriented programming (OOP): C++ supports classes, objects, inheritance, polymorphism, and encapsulation. This allows for modular, reusable code design.

  2. Multi-paradigm support: C++ supports procedural, object-oriented, generic, and functional programming styles — often within the same program.

  3. Strong static typing: Variables must be declared with explicit types. Implicit type conversions are narrowed; unsafe conversions require explicit casts (static_cast, reinterpret_cast, etc.).

  4. Templates and generic programming: Function and class templates allow type-independent code. Template metaprogramming enables compile-time computation. C++20 adds Concepts to constrain template parameters with readable, compiler-enforced predicates.

  5. Standard Template Library (STL): A comprehensive library of containers (vector, map, unordered_map, etc.), iterators, and algorithms. C++20 introduces the Ranges library, which enables composable, lazy pipeline-style algorithm chains.

  6. Memory management and RAII: C++ gives direct control over memory via new/delete and pointers, but modern C++ strongly favors RAII and smart pointers (std::unique_ptr, std::shared_ptr) to prevent leaks. Manual new/delete is considered a code smell in new code.

  7. Move semantics and rvalue references (C++11+): Enables efficient transfer of resources without copying. Foundational to writing performant modern C++.

  8. Exception handling: try/catch/throw provide structured error propagation. noexcept specifies that a function will not throw, enabling compiler optimizations.

  9. Concurrency support: C++11 introduced std::thread, mutexes, and condition variables. C++17 added parallel algorithms. C++20 adds coroutines (co_await, co_yield, co_return) and std::jthread.

  10. Modern additions (C++20/23):

    • Modules: Replace #include with import for faster builds and better encapsulation.
    • std::format / std::print: Type-safe, Python-style string formatting (C++20/23), replacing printf and stringstream hacks.
    • std::span: A non-owning view over contiguous data, replacing raw pointer + size pairs.
    • Three-way comparison (<=>): The "spaceship operator" auto-generates all six comparison operators.
  11. Low-level access: C++ retains C's ability to work directly with hardware — pointers, raw memory, bit manipulation — making it suitable for systems programming, embedded, and game development.

Common follow-up: "What would you choose C++ over other languages for?" — Performance-critical applications, systems/embedded programming, game engines, or any domain where you need both high-level abstractions and low-level control.

↑ Back to top

Follow-up 1

How does C++ support object-oriented programming?

C++ supports object-oriented programming (OOP) through the following features:

  1. Classes and objects: C++ allows for the creation of classes, which are user-defined data types that encapsulate data and functions. Objects are instances of classes.

  2. Inheritance: C++ supports inheritance, which allows a class to inherit properties and behaviors from another class. This promotes code reuse and enables the creation of hierarchies of classes.

  3. Polymorphism: C++ supports polymorphism, which allows objects of different classes to be treated as objects of a common base class. This enables the use of virtual functions and function overriding.

  4. Encapsulation: C++ supports encapsulation, which is the bundling of data and functions within a class. This provides data hiding and ensures that the internal implementation details of a class are hidden from external code.

Follow-up 2

What is the significance of the Standard Template Library (STL) in C++?

The Standard Template Library (STL) is a key component of C++ that provides a collection of generic algorithms and data structures. It is significant because:

  1. Reusability: The STL provides a set of reusable algorithms and data structures that can be used in various applications without the need for custom implementations.

  2. Efficiency: The algorithms and data structures in the STL are designed to be efficient and optimized, resulting in faster and more memory-efficient code.

  3. Standardization: The STL is part of the C++ standard library, which means that it is available on all compliant C++ compilers. This promotes portability and interoperability of code.

  4. Simplification: The STL simplifies the implementation of complex algorithms and data structures by providing high-level abstractions and generic interfaces.

Overall, the STL is a powerful tool that can greatly enhance the productivity and performance of C++ programmers.

Follow-up 3

How does C++ handle memory management?

C++ provides manual memory management, which means that the programmer is responsible for allocating and deallocating memory. C++ supports the following mechanisms for memory management:

  1. Stack allocation: Automatic variables and function parameters are allocated on the stack, and their memory is automatically deallocated when they go out of scope.

  2. Heap allocation: Dynamic memory allocation is done on the heap using the new operator. The programmer is responsible for deallocating the memory using the delete operator.

  3. Smart pointers: C++11 introduced smart pointers, which are objects that automatically manage the lifetime of dynamically allocated objects. Smart pointers, such as std::shared_ptr and std::unique_ptr, provide automatic deallocation of memory when the object is no longer needed.

  4. RAII (Resource Acquisition Is Initialization): C++ encourages the use of RAII, which is a programming technique that associates the acquisition and release of resources with the lifetime of an object. This ensures that resources, including memory, are properly managed and deallocated.

Follow-up 4

What is the role of constructors and destructors in C++?

Constructors and destructors are special member functions in C++ that are used to initialize and clean up objects, respectively.

  1. Constructors: Constructors are called when an object is created and are used to initialize the object's data members. They have the same name as the class and do not have a return type. Constructors can be overloaded to provide different ways of initializing objects.

  2. Destructors: Destructors are called when an object is destroyed and are used to clean up any resources allocated by the object. They have the same name as the class preceded by a tilde (~) and do not have any parameters or return type. Destructors are automatically called when an object goes out of scope or is explicitly deleted.

Constructors and destructors play a crucial role in managing the lifetime and initialization of objects in C++.

2. How does C++ differ from C?

C++ is a superset of C (with a small number of deliberate incompatibilities), but the two languages have diverged significantly in idiom and capability. Key differences:

  1. Object-Oriented Programming: C++ adds classes, objects, inheritance, polymorphism, and encapsulation. C has only structs (no methods, no access control).

  2. Templates and generic programming: C++ templates allow type-generic containers and algorithms at compile time. C relies on void* or macros for generics, which sacrifice type safety.

  3. Function and operator overloading: C++ allows multiple functions with the same name differing by parameter types. C does not support overloading.

  4. References: C++ adds reference types (int&), providing a safer alternative to pointers for aliasing. C only has pointers.

  5. Exception handling: C++ has built-in try/catch/throw. C uses error codes and setjmp/longjmp (which are fragile).

  6. Standard Template Library (STL): C++ ships with a rich library of containers, iterators, and algorithms. C's standard library is much smaller and lower-level.

  7. Namespaces: C++ namespaces prevent naming collisions across large codebases. C has a single global namespace.

  8. Memory management: Both support malloc/free, but C++ adds new/delete and, crucially, smart pointers (std::unique_ptr, std::shared_ptr) and RAII for safe, automatic resource management.

  9. bool type: C++ has a native bool. C89 lacks one (C99 added _Bool/stdbool.h).

  10. const semantics: In C++, const variables have internal linkage by default and are truly compile-time constants when used correctly. C's const is weaker and does not create compile-time constants usable in array sizes (without VLAs).

  11. Modern C++ additions (C++11–C++23): Move semantics, lambdas, auto type deduction, range-based for, coroutines, modules, concepts, std::format — none of these exist in C.

Key gotcha interviewers probe: C and C++ are not fully compatible. For example, C++ is stricter about void* conversions (must cast explicitly), inline has different semantics, and C99/C11 features like variable-length arrays (VLAs) and designated initializers were not in C++ until C++20. When asked about interoperability, mention extern "C" for calling C code from C++ (disables name mangling).

↑ Back to top

Follow-up 1

What additional features does C++ provide over C?

C++ provides several additional features over C, including:

  1. Object-Oriented Programming (OOP): C++ supports classes, objects, inheritance, and polymorphism, which allow for modular and reusable code.

  2. Templates: C++ introduces templates, which enable generic programming and the creation of reusable code.

  3. Exception Handling: C++ provides built-in exception handling mechanisms to handle runtime errors and exceptions.

  4. Standard Template Library (STL): C++ includes the STL, which provides a collection of classes and functions for common data structures and algorithms.

  5. Namespaces: C++ supports namespaces, which help in organizing code and avoiding naming conflicts.

  6. Function Overloading: C++ allows multiple functions with the same name but different parameters, enabling function overloading.

  7. Operator Overloading: C++ allows operators to be overloaded, enabling custom definitions for operators like +, -, *, etc.

Follow-up 2

How does memory management in C++ differ from that in C?

Memory management in C++ differs from that in C in the following ways:

  1. Dynamic Memory Allocation: C++ provides the 'new' and 'delete' operators for dynamic memory allocation and deallocation, which are more flexible and safer than the 'malloc' and 'free' functions used in C.

  2. Constructors and Destructors: C++ introduces constructors and destructors, which are special member functions used for initializing and cleaning up objects. These features help in managing memory automatically.

  3. RAII (Resource Acquisition Is Initialization): C++ encourages the use of RAII, where resources are acquired during object creation and released during object destruction. This helps in automatic memory management and prevents resource leaks.

  4. Smart Pointers: C++ provides smart pointers like 'unique_ptr', 'shared_ptr', and 'weak_ptr', which help in automatic memory management by providing automatic deallocation when the object is no longer needed.

  5. Garbage Collection: C++ does not have built-in garbage collection like some other languages, such as Java or C#. Memory deallocation is typically done manually or using smart pointers.

Follow-up 3

Can you give an example of a scenario where C++ would be a better choice than C?

C++ would be a better choice than C in scenarios where:

  1. Object-Oriented Programming (OOP) is required: If the project involves complex data structures, inheritance, polymorphism, or other OOP concepts, C++ provides better support for these features.

  2. Reusability and Modularity are important: C++ supports classes and objects, which allow for code reusability and modularity. This can lead to faster development and easier maintenance.

  3. Performance is critical: C++ allows low-level programming and direct memory manipulation, which can result in more efficient code execution compared to C.

  4. Libraries and Frameworks: Many popular libraries and frameworks are written in C++, so if the project requires the use of these libraries, it would be more convenient to use C++.

  5. GUI Applications: C++ has better support for creating graphical user interfaces (GUI) compared to C, with libraries like Qt and wxWidgets.

It's important to note that the choice between C and C++ depends on the specific requirements of the project and the expertise of the development team.

3. What is the significance of the main function in C++?

The main function is the mandatory entry point of every C++ program — execution begins here after global object construction and ends when main returns (or std::exit is called).

Standard signatures:

int main()                            // no command-line arguments
int main(int argc, char* argv[])      // command-line arguments
int main(int argc, char* argv[], char* envp[])  // + environment (platform extension)

The return type must be int. Returning 0 (or falling off the end of main — unique among C++ functions) signals success to the OS. Any non-zero value signals failure; portable programs use EXIT_SUCCESS and EXIT_FAILURE from ``.

Key points interviewers ask about:

  • Only one main per program. It cannot be overloaded, called recursively (technically undefined behaviour), or taken by address.
  • argc and argv: argc is the count of arguments (at least 1, since argv[0] is conventionally the program name). argv[argc] is guaranteed to be nullptr.
  • Global constructors run before main. If a global object's constructor throws, main is never reached. This is why heavy logic in global constructors is a code smell.
  • Destructors of local objects in main run on normal return. std::exit() does not call them, which can skip RAII cleanup — use std::atexit or prefer normal return.
  • WinMain / wmain (Windows): Windows GUI programs use WinMain as the OS entry point, but the C++ runtime still calls the standard main behind the scenes in many frameworks.

Common follow-up: "What happens before main is called?" — The C++ runtime initialises static-duration objects with non-trivial constructors (in translation-unit order, which is unspecified across TUs — the "static initialisation order fiasco"), then calls main.

↑ Back to top

Follow-up 1

Can the main function in C++ return a value?

Yes, the main function in C++ can return a value. The return type of the main function is int, which means it can return an integer value. By convention, a return value of 0 is used to indicate successful execution of the program, while any non-zero value indicates an error or abnormal termination.

Follow-up 2

Can the main function in C++ take arguments?

Yes, the main function in C++ can take arguments. The arguments to the main function are passed through the command line when the program is executed. The main function can have two parameters: argc, which represents the number of command line arguments, and argv, which is an array of strings containing the actual arguments.

Follow-up 3

What would happen if a C++ program didn't have a main function?

If a C++ program doesn't have a main function, the program will not be able to execute. The compiler will generate an error and the program will fail to compile.

4. How are variables declared and initialized in C++?

In C++, variables are declared by writing the type followed by the variable name. Initialization can happen in several forms, and modern C++ strongly prefers uniform (brace) initialization introduced in C++11.

Forms of initialization:

// Copy initialization (C-style)
int a = 5;

// Direct initialization
int b(10);

// Uniform (brace) initialization — preferred in modern C++ (C++11+)
int c{15};           // prevents narrowing conversions — compiler error if value doesn't fit
double d{3.14};

// Default initialization (uninitialized — undefined value for built-ins)
int e;               // dangerous: holds garbage; always initialize

// Value initialization (zero-initializes built-in types)
int f{};             // f == 0
double g{};          // g == 0.0

// auto type deduction (C++11+)
auto h = 42;         // int
auto i = 3.14;       // double
auto j = "hello"s;   // std::string (with using namespace std::string_literals)

Key points interviewers probe:

  • Narrowing conversions: Brace initialization {} is the only form that makes narrowing a compile-time error. int x{3.7}; won't compile; int x = 3.7; silently truncates.
  • const and constexpr: const marks a variable as read-only. constexpr (C++11) means the value must be known at compile time and can appear in constant expressions (array sizes, template arguments, etc.).
const int maxSize = 100;         // runtime const
constexpr int bufferSize = 256;  // compile-time constant
  • auto: Let the compiler deduce the type. Particularly useful with complex iterator types or lambda return types. Use const auto& to avoid unintended copies when iterating.
  • Structured bindings (C++17): Destructure aggregates, pairs, and tuples directly.
auto [key, value] = std::make_pair(1, "one");
  • std::optional (C++17): For variables that may or may not hold a value, prefer std::optional over sentinel values like -1 or nullptr.

Best practice: Always initialize variables at the point of declaration. Uninitialized built-in type variables contain indeterminate values — reading them is undefined behaviour.

↑ Back to top

Follow-up 1

What are the different data types available in C++?

C++ provides several built-in data types, including:

  • int: used to store integer values
  • float and double: used to store floating-point numbers
  • char: used to store single characters
  • bool: used to store boolean values (true or false)
  • string: used to store sequences of characters

There are also modifiers that can be applied to these data types to specify their size and range, such as short, long, and unsigned.

Follow-up 2

What is the scope and lifetime of variables in C++?

The scope of a variable in C++ refers to the region of the program where the variable is visible and can be accessed. The lifetime of a variable refers to the period during which the variable exists in memory.

In C++, variables can have different scopes:

  • Global scope: Variables declared outside of any function or class have global scope and can be accessed from anywhere in the program.
  • Local scope: Variables declared within a function or block have local scope and can only be accessed within that function or block.

The lifetime of a variable depends on its scope:

  • Global variables have a lifetime that extends throughout the entire execution of the program.
  • Local variables have a lifetime that starts when the function or block is entered and ends when the function or block is exited.

Follow-up 3

What is the difference between declaring and defining a variable in C++?

In C++, declaring a variable means providing its type and name, while defining a variable means allocating memory for it and optionally initializing it.

For example:

// Declaration
extern int count;

// Definition
int count = 10;

5. What are the different types of loops in C++?

C++ provides three classic loop constructs plus a modern range-based form:

1. for loop — use when the iteration count or range bounds are known up front.

for (int i = 0; i < 10; ++i) {
    std::cout << i << '\n';
}

2. Range-based for loop (C++11+) — the preferred way to iterate over any range (array, container, or anything providing begin()/end()). Use const auto& to avoid copies.

std::vector v{1, 2, 3, 4, 5};
for (const auto& x : v) {
    std::cout << x << '\n';
}

With C++20 Ranges you can also iterate lazily over transformed or filtered views without copying:

for (auto x : v | std::views::filter([](int n){ return n % 2 == 0; })) {
    std::cout << x << '\n';
}

3. while loop — use when the loop should continue as long as a condition is true and the number of iterations is not known in advance.

int n = 1;
while (n < 100) {
    n *= 2;
}

4. do-while loop — guarantees the body executes at least once before the condition is checked.

int choice;
do {
    std::cout << "Enter a positive number: ";
    std::cin >> choice;
} while (choice <= 0);

Loop control statements:

Statement Effect
break Exits the innermost loop immediately
continue Skips the rest of the current iteration
goto Avoid — jumps break RAII and readability

Common interview gotchas:

  • Prefer ++i over i++ for non-trivial iterators (avoids creating a temporary copy).
  • Infinite loops: for (;;) or while (true) are idiomatic; always have a reachable break or return.
  • Range-based for with auto (not auto&) copies each element — a silent performance bug for large objects.
↑ Back to top

Follow-up 1

How does a for loop work in C++?

A for loop in C++ consists of three parts: initialization, condition, and increment/decrement. The initialization part is executed only once at the beginning. Then, the condition is checked. If the condition is true, the loop body is executed. After each iteration, the increment/decrement part is executed. The loop continues until the condition becomes false.

Follow-up 2

What is the difference between a while loop and a do-while loop in C++?

The main difference between a while loop and a do-while loop in C++ is that the condition is checked before the execution of the loop body in a while loop, whereas in a do-while loop, the condition is checked after the execution of the loop body. This means that a do-while loop will always execute the loop body at least once, even if the condition is initially false.

Follow-up 3

Can you provide an example of a situation where a do-while loop would be more appropriate than a for loop?

Sure! Let's say you want to prompt the user for input until they enter a valid number. In this case, a do-while loop would be more appropriate because you want to execute the loop body at least once, regardless of the initial condition. Here's an example:

int number;
do {
    cout << "Enter a number: ";
    cin >> number;
} while (number <= 0);

Live mock interview

Mock interview: Basics of C++

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.

Next lesson Input/Output in C++ →