System Programming Topic

30 C++ Interview Questions and Answers

Basic C++ Concepts

1. What is the difference between C and C++?

Answer:

  • C is procedural, while C++ supports both procedural and object-oriented programming

  • C++ supports features like classes, objects, inheritance, polymorphism, encapsulation

  • C++ has additional features like function overloading, operator overloading, references, exception handling, templates, and namespaces

  • C++ provides stronger type checking and better memory management with constructors/destructors

2. What are the four pillars of OOP in C++?

Answer:

  • Encapsulation: Bundling data and methods that operate on that data, restricting direct access

  • Inheritance: Creating new classes from existing ones, promoting code reuse

  • Polymorphism: Ability of objects to take multiple forms (compile-time via overloading, runtime via overriding)

  • Abstraction: Hiding implementation details and showing only essential features

3. What is the difference between struct and class in C++?

Answer:

cpp

// The only difference is default access specifier
struct MyStruct {     // members are public by default
    int x;
};

class MyClass {       // members are private by default
    int x;
};

Memory Management

4. What is the difference between new/delete and malloc()/free()?

Answer:

  • new calls constructor, delete calls destructor; malloc/free don't

  • new returns proper type pointer, malloc returns void*

  • new can be overloaded, malloc cannot

  • new throws bad_alloc on failure, malloc returns NULL

  • new is an operator, malloc is a function

5. What are smart pointers in C++? Explain types.

Answer:
Smart pointers automatically manage memory to prevent leaks:

cpp

#include <memory>
// 1. unique_ptr: Exclusive ownership, cannot be copied
std::unique_ptr<int> ptr1 = std::make_unique<int>(10);

// 2. shared_ptr: Shared ownership with reference counting
std::shared_ptr<int> ptr2 = std::make_shared<int>(20);

// 3. weak_ptr: Non-owning reference to shared_ptr
std::weak_ptr<int> weak = ptr2;

6. What is RAII (Resource Acquisition Is Initialization)?

Answer:
RAII is a programming idiom where resource allocation is tied to object lifetime:

  • Resources are acquired in constructor

  • Resources are released in destructor

  • Ensures exception safety and prevents resource leaks

cpp

class FileHandler {
    FILE* file;
public:
    FileHandler(const char* filename) : file(fopen(filename, "r")) {}
    ~FileHandler() { if(file) fclose(file); }
    // File automatically closes when object goes out of scope
};

Functions and Classes

7. What is function overloading vs overriding?

Answer:

  • Overloading: Same function name with different parameters (compile-time polymorphism)

  • Overriding: Redefining base class function in derived class (runtime polymorphism)

cpp

// Overloading
void print(int x) { }
void print(double x) { }  // Different parameters

// Overriding
class Base { virtual void show() { } };
class Derived : public Base { void show() override { } }; // Same signature

8. What are virtual functions and pure virtual functions?

Answer:

cpp

class Base {
public:
    virtual void show() { }      // Virtual function - can be overridden
    virtual void pure() = 0;     // Pure virtual function - must be overridden
};

class Derived : public Base {
public:
    void show() override { }     // Overrides base implementation
    void pure() override { }     // Must implement pure virtual function
};
  • Virtual functions enable runtime polymorphism

  • Class with pure virtual function becomes abstract class (cannot be instantiated)

9. What are constructors and destructors? Explain types.

Answer:

  • Default Constructor: No parameters

  • Parameterized Constructor: Takes parameters

  • Copy Constructor: Creates object from another object

  • Move Constructor (C++11): Transfers resources

  • Destructor: Cleans up when object is destroyed

cpp

class Example {
    int* data;
public:
    Example() {}                             // Default
    Example(int x) {}                        // Parameterized
    Example(const Example& other) {}         // Copy constructor
    Example(Example&& other) noexcept {}     // Move constructor
    ~Example() { delete data; }              // Destructor
};

Advanced Concepts

10. What are templates? Explain function and class templates.

Answer:
Templates enable generic programming:

cpp

// Function template
template<typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

// Class template
template<class T>
class Stack {
    T elements[100];
public:
    void push(T element);
    T pop();
};

// Usage
int x = max<int>(5, 10);
Stack<string> stringStack;

11. What is the difference between stack and heap memory?

Answer:

Stack Heap
Fixed size Dynamic size
Automatic allocation/deallocation Manual (or smart pointer) management
Faster access Slower access
Local variables Dynamic allocation (new/malloc)
Limited size Larger size available
LIFO order No specific order

12. What is exception handling in C++?

Answer:

cpp

try {
    if(error) throw runtime_error("Error occurred");
    // Code that might throw
} 
catch(const runtime_error& e) {
    cout << "Caught: " << e.what();
}
catch(...) {
    cout << "Unknown exception";
}
  • try: Code that might throw exceptions

  • catch: Handles specific exceptions

  • throw: Throws an exception

  • noexcept (C++11): Specifies function won't throw

C++11/14/17 Features

13. What is auto keyword and decltype?

Answer:

cpp

auto x = 10;            // x is int
auto y = 3.14;          // y is double

vector<int> vec = {1, 2, 3};
for(auto& num : vec) {  // Range-based for loop
    cout << num;
}

decltype(x) z = 20;     // z has same type as x (int)

14. What are lambda expressions?

Answer:

cpp

// Basic lambda
auto sum = [](int a, int b) { return a + b; };

// With capture list
int factor = 2;
auto multiply = [factor](int x) { return x * factor; };

// Generic lambda (C++14)
auto generic = [](auto a, auto b) { return a + b; };

// Mutable lambda
auto counter = [count = 0]() mutable { return ++count; };

15. What is move semantics and rvalue references?

Answer:

cpp

class String {
    char* data;
public:
    // Move constructor
    String(String&& other) noexcept 
        : data(other.data) {
        other.data = nullptr;  // Steal resources
    }
    
    // Move assignment
    String& operator=(String&& other) noexcept {
        if(this != &other) {
            delete[] data;
            data = other.data;
            other.data = nullptr;
        }
        return *this;
    }
};

String s1 = "Hello";
String s2 = std::move(s1);  // Move, not copy

STL Questions

16. Explain important STL containers.

Answer:

  • Sequence: vector, deque, list, array, forward_list

  • Associative: set, multiset, map, multimap (ordered)

  • Unordered: unordered_set, unordered_map (hash-based)

  • Container adapters: stack, queue, priority_queue

17. What are iterators? Explain types.

Answer:
Iterators provide access to container elements:

  • Input: Read-only, forward movement

  • Output: Write-only, forward movement

  • Forward: Read/write, forward movement

  • Bidirectional: Read/write, forward/backward (list, set, map)

  • Random-access: Direct access (vector, deque, array)

18. What is the difference between vector and list?

Answer:

Vector List
Dynamic array Doubly linked list
Contiguous memory Non-contiguous memory
Random access O(1) Sequential access O(n)
Insert/delete at end: O(1) Insert/delete anywhere: O(1)
Insert/delete middle: O(n) No reallocation needed
Cache friendly Cache unfriendly

Advanced Questions

19. What is vtable and vptr?

Answer:

  • vtable: Virtual table storing pointers to virtual functions

  • vptr: Virtual pointer in each object pointing to vtable

  • Created for classes with virtual functions

  • Enables runtime polymorphism

cpp

class Base { virtual void f() {} };
Base b;
// b has hidden vptr pointing to Base's vtable

20. What is the rule of three/five/zero?

Answer:

  • Rule of Three: If you need to define any of destructor, copy constructor, or copy assignment, you likely need all three

  • Rule of Five (C++11): Add move constructor and move assignment to rule of three

  • Rule of Zero: Let compiler generate special member functions; use RAII classes for resources

21. What is SFINAE?

Answer:
Substitution Failure Is Not An Error - template mechanism where invalid substitutions don't cause errors but remove candidates:

cpp

template<typename T>
auto test(T t) -> decltype(t.size(), void()) {
    // This version only for types with .size() method
}

template<typename T>
void test(T t) {
    // Fallback version
}

More Questions & Answers

22. What is const correctness?

Answer:
Using const to prevent modification:

cpp

const int x = 5;                    // Constant value
const int* ptr = &x;                // Pointer to constant
int* const ptr = &y;                // Constant pointer
const int* const ptr = &x;          // Constant pointer to constant

void func(const string& str);       // Won't modify parameter
const int getValue() const;         // const member function

23. What is the difference between shallow and deep copy?

Answer:

cpp

// Shallow copy - copies pointers, not pointed data
class Shallow {
    int* data;
public:
    Shallow(const Shallow& other) : data(other.data) {}
};

// Deep copy - copies pointed data
class Deep {
    int* data;
public:
    Deep(const Deep& other) : data(new int(*other.data)) {}
    ~Deep() { delete data; }
};

24. What are friend functions and classes?

Answer:

cpp

class A {
private:
    int secret;
    friend void showSecret(A& a);           // Friend function
    friend class B;                         // Friend class
};

void showSecret(A& a) {
    cout << a.secret;  // Can access private
}

class B {
public:
    void peek(A& a) {
        cout << a.secret;  // Can access private
    }
};

25. What are inline functions?

Answer:

  • Suggestion to compiler to insert function code at call site

  • Avoids function call overhead

  • Useful for small, frequently called functions

  • Defined in header files

cpp

inline int square(int x) {
    return x * x;
}
// Compiler may inline: int result = 5 * 5;

26. What is namespace and its purpose?

Answer:

cpp

namespace MySpace {
    int x;
    void func() {}
}

using namespace MySpace;  // Bring all into scope
using MySpace::x;         // Bring only x

namespace A::B::C {       // Nested namespace (C++17)
    int value;
}
  • Prevents name collisions

  • Organizes code logically

  • std is standard namespace

27. What is the diamond problem and how to solve it?

Answer:

cpp

class A { public: void f() {} };
class B : virtual public A {};  // Virtual inheritance
class C : virtual public A {};
class D : public B, public C {}; // Only one A subobject

D d;
d.f();  // No ambiguity with virtual inheritance

28. What is RTTI (Runtime Type Information)?

Answer:
Mechanism to determine object type at runtime:

cpp

Base* ptr = new Derived();
if(Derived* d = dynamic_cast<Derived*>(ptr)) {
    // Successful cast
}

typeid(*ptr).name();  // Get type name

29. Explain copy elision and return value optimization (RVO)

Answer:
Compiler optimization to avoid unnecessary copies:

cpp

vector<int> createVector() {
    return vector<int>{1, 2, 3};  // RVO: constructed directly in caller
}

vector<int> v = createVector();  // No copy/move happens

30. What are the differences between pointers and references?

Answer:

Pointers References
Can be NULL Must be initialized
Can be reassigned Cannot be reassigned
Has own memory address Alias, no separate memory
Supports arithmetic No arithmetic
Can have multiple levels Single level
-> operator for access . operator for access
Can point to array Cannot reference array

These questions cover a broad range of C++ concepts commonly tested in interviews. Practice implementing these concepts and be prepared to write code during the interview.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?