Programming using C++
Interview Questions with Answers

What are the key features of C++?

Answer:

C++ is a multi-paradigm programming language that supports both procedural and object-oriented programming. Key features include:

  • Object-Oriented Programming (Classes, Objects, Inheritance, Polymorphism, Abstraction, Encapsulation)
  • Templates (Generic programming)
  • Standard Template Library (STL)
  • Operator and Function Overloading
  • Exception Handling
  • Dynamic Memory Management (new, delete)
  • Namespaces (to avoid naming conflicts)
  • Support for Low-Level Programming (pointers, inline assembly)
  • RAII (Resource Acquisition Is Initialization)
  • Modern features from C++11, C++14, C++17, and C++20
  • C++ supports multithreading with the <thread> library (from C++11 onwards), enabling concurrent execution and parallel programming.
  • Introduced in C++11, lambdas allow writing anonymous functions inline, useful for short functions especially in STL algorithms.

Boost your confidence with the most asked C++ interview questions!

2. How is C++ different from C?

Answer:

FeatureC

C++

Programming ParadigmProceduralMulti-paradigm (Procedural + OOP)
Object-Oriented SupportNoYes (classes, inheritance, polymorphism, etc.)
Function OverloadingNot supportedSupported
NamespaceNot availableAvailable
Templates/GenericsNot supportedFully supported
Standard LibraryLimited (stdio.h, etc.)Rich (STL: vector, map, set, etc.)
Exception HandlingManual (via return codes)Try-catch blocks supported

 

3. What is a namespace in C++?

Answer:

A namespace in C++ is used to avoid name conflicts by grouping entities (functions, classes, variables) under a name.

Example:

#include <iostream>
namespace Learn2Earn {
    void greet() {
        std::cout << "Welcome to C++!" << std::endl;
    }
}
int main() {
    Learn2Earn::greet();
    return 0;
}

Namespaces help manage large codebases and libraries where multiple modules may have same-named entities.

4. What is the role of the main() function in C++?

Answer:

The main() function is the entry point of any C++ program.

Features:

  • Must return an int (commonly returns 0 for success).
  • Can accept arguments: int main(int argc, char* argv[])
  • C++ allows both:
    • int main()
    • int main(int argc, char* argv[])

 Example:

int main() {
    std::cout << "Hello, World!";
    return 0;
}

Without main(), a C++ program cannot execute.

5. What are the new features introduced in C++11 and C++17?

Answer:

C++11 Key Features:

  • auto keyword
  • nullptr (replaces NULL)
  • Range-based for loop
  • Lambda expressions
  • Move semantics and rvalue references
  • Smart pointers (unique_ptr, shared_ptr)
  • static_assert, decltype, constexpr
  • Thread support (multi-threading)

C++17 Key Features:

  • if constexpr for compile-time conditions
  • Structured bindings (auto [a, b] = pair)
  • std::optional, std::variant, std::any
  • std::filesystem
  • inline variables
  • Template argument deduction
  • Improved performance and standard compliance

6. What are tokens in C++?

Answer:

Tokens are the smallest elements of a C++ program that are meaningful to the compiler.

Types of Tokens:

  1. Keywords – int, return, class, public, etc.
  2. Identifiers – Variable and function names
  3. Literals – Constants (10, 3.14, ‘A’, “Hello”)
  4. Operators – +, -, *, /, =, etc.
  5. Punctuators – ;, {}, (), [], etc.
  6. Comments – // or /* */

Every C++ program is composed of tokens.

7. What is a reference variable in C++?

Answer:

A reference variable is an alias for another variable. It must be initialized during declaration and refers to the same memory.

Syntax:

int a = 10;
int &ref = a;     // ref is a reference to a

Use Cases:

  • Efficient parameter passing
  • Function return by reference
  • Used in range-based loops and operator overloading

8. What is the use of the auto keyword in C++?

Answer:

The auto keyword automatically deduces the type of the variable from the initializer expression.

Example:

auto x = 10;           // int
auto y = 3.14;         // double
auto name = "John";    // const char*

Benefits:

  • Cleaner and more readable code
  • Especially useful in templates, STL iterators, and lambda expressions

9. What is the difference between cin and scanf()?

Answer:

Feature

cin (C++)

scanf() (C)

Type SafetyType-safeNot type-safe
Syntax SimplicityCleaner: cin >> var;Verbose: scanf(“%d”, &var);
OverloadingSupports overloadingDoes not support overloading
Format SpecifiersNot requiredRequired (%d, %f, etc.)
Used InC++C and also in C++ (but not preferred)

 

10. What are the basic I/O operations in C++?

Answer:

C++ uses streams for I/O operations:

Operation

Stream Object

Example

Inputcincin >> name;
Outputcoutcout << “Hello”;
Errorcerrcerr << “Error!” << endl;
Logclogclog << “Logged data”;

Example:

#include <iostream>
using namespace std;
int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "You entered: " << age << endl;
    return 0;
}

11. What are the four pillars of Object-Oriented Programming?

Answer:

The four pillars of OOP are:

  1. Encapsulation – Binding data and methods into a single unit (class), and restricting access using access specifiers.
  2. Abstraction – Hiding internal implementation and showing only essential features.
  3. Inheritance – Acquiring properties and behaviors of one class into another.
  4. Polymorphism – Ability to take many forms (e.g., function overloading, overriding).

These principles make OOP powerful, modular, and reusable.

12. What is the difference between a class and an object?

Answer:

Feature

Class

Object

DefinitionBlueprint/template for objectsReal-world instance of a class
MemoryNo memory until object is createdOccupies memory during runtime
Declarationclass Car { … };Car c1;
PurposeDefines structure and behaviorUses structure and behavior defined in class

 

13. What is encapsulation? Give a real-world example.

Answer:

Encapsulation is the bundling of data and methods that operate on that data, while restricting direct access to internal details.

Example:

In a bank account class:

    class BankAccount {

private:

    double balance;

public:

    void deposit(double amount) { balance += amount; }
    void withdraw(double amount) { if (balance >= amount) balance -= amount; }
    double getBalance() { return balance; }
};
  • Data (balance) is hidden (private).
  • Access is provided through public methods.

Encapsulation ensures data protection and controlled access.

14. What is inheritance in C++? How does it work?

Answer:

Inheritance allows a class (child/derived) to acquire the properties and behavior of another class (parent/base).

Syntax:

class Vehicle {
public:
    void move() { cout << "Moving..." << endl; }
};
class Car : public Vehicle {
public:
    void honk() { cout << "Beep Beep!" << endl; }
};

Types of Inheritance:

  • Single
  • Multiple
  • Multilevel
  • Hierarchical
  • Hybrid

Enables code reuse and supports polymorphism.

15. What is function overloading and operator overloading?

Answer:

Function Overloading: Defining multiple functions with the same name but different parameters.

void print(int a);
void print(double b);
void print(string s);

Operator Overloading: Giving custom behavior to operators for user-defined types.

class Complex {

public:

    int real, imag;
    Complex operator+(const Complex& c) {
        Complex temp;
        temp.real = real + c.real;
        temp.imag = imag + c.imag;
        return temp;
    }
};

Both are examples of compile-time polymorphism.

16. What is polymorphism in C++?

Answer:

Polymorphism means “many forms” – the ability of a function, method, or operator to behave differently based on context.

Types:

  • Compile-time Polymorphism (Static)
    • Function overloading
    • Operator overloading
  • Run-time Polymorphism (Dynamic)
    • Achieved using virtual functions and inheritance

Allows code to be extensible and flexible.

17. What is the difference between compile-time and run-time polymorphism?

Answer:

FeatureCompile-Time PolymorphismRun-Time Polymorphism
When ResolvedAt compile timeAt run time
Technique UsedFunction/operator overloadingVirtual functions + pointers
PerformanceFaster (no overhead)Slightly slower (uses vtable)

Example:

Compile-time:

void print(int x);
void print(double y);

Run-time:

class Base {
public:
    virtual void show() { cout << "Base\n"; }
};
class Derived : public Base {
public:
    void show() override { cout << "Derived\n"; }
};

18. What is abstraction? How is it implemented in C++?

Answer:

Abstraction is the concept of hiding implementation details and showing only essential features to the user.

Ways to Implement Abstraction:

  1. Abstract Classes (contain pure virtual functions)
  2. Interfaces (via only pure virtual methods)

Example:

class Shape {
public:
    virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {

public:

    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};

Promotes interface-based design and loose coupling.

19. What are access specifiers?

Answer:

Access specifiers control the visibility of class members (data/functions) outside the class.

SpecifierAccessible within classDerived class

Outside class

publicYesYesYes
protectedYesYesNo
privateYesNoNo

 Example:

class Test {

public:

    int a;          // accessible everywhere

protected:

    int b;          // accessible in subclass

private:

    int c;          // accessible only within Test
};

20. What is the use of this pointer?

Answer:

The this pointer is an implicit pointer available inside non-static member functions that refers to the current object.

Uses:

  • To access data members that may be shadowed by local variables.
  • To return the object itself from a function (method chaining).
  • To pass the current object as a parameter.

Example:

class Employee {
    int id;
public:
    Employee(int id) { this->id = id; }
    Employee& setId(int id) {
        this->id = id;
        return *this;
    }
    void show() {
        cout << "ID: " << this->id << endl;
    }
};

Prepare smartly and land your dream job in programming!

21. What is a constructor? Types of constructors in C++?

Answer:

A constructor is a special member function of a class that is automatically invoked when an object is created. It initializes the object.

 Characteristics:

  • Has the same name as the class
  • No return type
  • Can be overloaded

 Types of Constructors:

  1. Default Constructor – Takes no parameters
  2. Parameterized Constructor – Accepts arguments
  3. Copy Constructor – Initializes an object using another object
  4. Dynamic Constructor – Allocates memory dynamically (uses new)
  5. Constructor with Initialization List

22. What is a copy constructor?

Answer:

A copy constructor is used to initialize a new object as a copy of an existing object. 

Syntax:

ClassName(const ClassName &obj);

Example:

class Student {
    int id;
public:
    Student(int x) { id = x; }
    Student(const Student &s) { id = s.id; }
};
  • If not defined explicitly, C++ provides a default copy constructor.
  • Required when objects have pointers or dynamic memory (to avoid shallow copies).

23. What is a destructor? When is it called?

Answer:

A destructor is a special member function that is automatically called when an object goes out of scope or is explicitly deleted. It is used to free resources like dynamic memory.

Syntax:

~ClassName();

Characteristics:

  • No parameters, no return type.
  • Cannot be overloaded.
  • Only one destructor per class.

Example:

class A {
public:
    ~A() {
        cout << "Destructor called\n";
    }
};

24. What is the difference between a constructor and a method?

Answer:

FeatureConstructor

Method (Member Function)

PurposeInitializes the objectDefines behavior or operations
NameSame as classAny valid identifier
Return TypeNo return typeMust have return type
InvocationAutomatically called when object is createdManually called using object
OverloadingYesYes

 

25. Can constructors be virtual? Why or why not?

Answer:

No, constructors cannot be virtual in C++.

Reason:

  • Constructors are invoked to create objects.
  • Virtual functions require a vtable, which is set up after the constructor runs.
  • Making constructor virtual would require vtable access before it’s constructed — which is not possible.

However, destructors can and should be virtual in polymorphic base classes.

 

26. Can a constructor be overloaded?

Answer:

Yes, constructors can be overloaded in C++.

Meaning:

A class can have multiple constructors with different parameter lists to allow various ways of initialization.

Example:

class Person {
public:
    Person() { }
    Person(string name) { }
    Person(string name, int age) { }
};

Enables constructor flexibility.

 

27. What is a default constructor?

Answer:

A default constructor is a constructor that takes no parameters (or all parameters have default values).

Example:

class Test {
public:
    Test() {
        cout << "Default constructor called\n";
    }
};

Note:

  • If no constructor is provided, C++ automatically generates a default constructor.
  • If any other constructor is defined, the default is not provided automatically unless explicitly defined.

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

Answer:

Copy TypeShallow Copy

Deep Copy

BehaviorCopies only pointer addressesCopies actual data and creates new memory
ConsequenceBoth objects share same memoryBoth objects are completely independent
Use CaseSafe for primitive typesRequired for dynamic memory/pointers

Example:

class A {
    int* ptr;

public:

    A(int x) { ptr = new int(x); }
    // Deep copy constructor
    A(const A &obj) {
        ptr = new int(*obj.ptr);
    }
    ~A() { delete ptr; }
};

29. What happens if you don’t define a destructor?

Answer:

If you don’t define a destructor:

  • C++ provides a default destructor.
  • For classes that do not manage resources manually, this is fine.
  • BUT if your class allocates memory (e.g., with new), not defining a destructor leads to memory leaks.

Always define a destructor when your class allocates dynamic memory or resources (file handles, sockets, etc.).

 

30. What is constructor initialization list?

Answer:

A constructor initialization list is a more efficient way to initialize data members and base classes in C++.

 Syntax:

class Student {
    int id;
    string name;
public:
    Student(int i, string n) : id(i), name(n) { }
};

Benefits:

  • Initializes const and reference members (which must be initialized once).
  • Efficient for initializing base classes and large objects.
  • Avoids default constructor followed by assignment.

31. What are the types of inheritance in C++?

Answer:

C++ supports five types of inheritance:

  1. Single Inheritance – One base and one derived class.
  2. Multiple Inheritance – A class inherits from more than one base class.
  3. Multilevel Inheritance – Class derived from another derived class.
  4. Hierarchical Inheritance – Multiple classes inherit from a single base class.
  5. Hybrid Inheritance – Combination of any of the above, often leads to diamond problem.

32.What is multiple inheritance?

Answer:

Multiple Inheritance is when a derived class inherits from more than one base class.

Syntax:

class A { };
class B { };
class C : public A, public B { };  // C inherits from A and B

It allows combining features from multiple sources, but may cause ambiguity (like same function in both A and B).

 

33. How is ambiguity resolved in multiple inheritance?

Answer:

Ambiguity occurs when two base classes have members with the same name.

Resolved using scope resolution operator :::

class A {

public:

    void display() { cout << "A\n"; }
};
class B {

public:

    void display() { cout << "B\n"; }
};
class C : public A, public B {

public:

    void show() {
        A::display();  // Resolving ambiguity
        B::display();
    }
};

34. What is the diamond problem in C++?

Answer:

It occurs in multiple inheritance when two base classes inherit from the same grandparent, and a derived class inherits from both, causing duplicate copies of the grandparent.

Example:

    A
   / \
  B   C
   \ /
    D
  • Class D gets two copies of class A (via B and C).
  • Leads to ambiguity (e.g., A::display() – which one?).

35. How does virtual inheritance solve the diamond problem?

Answer:

Using virtual inheritance, we tell the compiler to share the base class between multiple paths, avoiding duplication. 

Example:

class A { public: void show() { cout << "A\n"; } };
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };

Now, class D has only one copy of class A, avoiding ambiguity.

 

36. What is the difference between virtual and pure virtual functions?

Answer:

FeatureVirtual Function

Pure Virtual Function

DefinitionHas a body in base classNo body in base class (assigned = 0)
UsageOptional to overrideMust be overridden in derived class
Abstract class required?NoYes

Example:

class A {

public:

    virtual void show() { cout << "A\n"; }           // Virtual
    virtual void draw() = 0;                         // Pure Virtual
};

37. What is an abstract class?

Answer:

An abstract class is a class that contains at least one pure virtual function. It cannot be instantiated, and is meant to be a base class.

Example:

class Shape {

public:

    virtual void draw() = 0;  // Pure virtual function

};

Used to define interfaces and polymorphic behavior in OOP.

 

38. What is function overriding?

Answer:

Function Overriding allows a derived class to provide a specific implementation of a method that is already defined in the base class.

Rules:

  • Must have same name, parameters, and return type.
  • Base class function should be virtual.
  • Uses runtime polymorphism.

Example:

class Animal {

public:

    virtual void sound() { cout << "Animal sound\n"; }
};
class Dog : public Animal {

public:

    void sound() override { cout << "Dog barks\n"; }
};

39. What is a virtual table (vtable)?

Answer:

A vtable is a hidden lookup table created by the compiler for classes with virtual functions.

  • Contains addresses of virtual functions.
  • Every object with virtual functions contains a hidden pointer to its class’s vtable.
  • Enables dynamic dispatch at runtime.

40. What is dynamic dispatch?

Answer:

Dynamic dispatch is the process by which a function call is resolved at runtime, based on the actual type of the object, not the pointer type.

 Enabled by:

  • Virtual functions
  • Vtable mechanism

Example:

Animal* a = new Dog();
a->sound();  // Calls Dog's sound() due to dynamic dispatch

Enables runtime polymorphism and flexibility in designing extensible applications.

Don’t just learn C++, master it with real interview-ready answers!

41. What is the difference between new and malloc()?

Answer:
Feature new (C++)

malloc() (C)

Language C++ C
Syntax int* p = new int; int* p = (int*) malloc(sizeof(int));
Constructor Call Calls constructor (for objects) Does not call constructor
Type Safety Type-safe Not type-safe (requires casting)
Return Value Correct type void* (must be cast)
Failure Behavior Throws bad_alloc exception Returns NULL
Deallocation delete free()

42. What is delete and how is it used?

Answer: The delete operator in C++ is used to deallocate memory allocated by new. Syntax:
int* ptr = new int;
delete ptr;  // Frees memory
int* arr = new int[5];
delete[] arr;  // For arrays
Always pair new with delete, and new[] with delete[].

43. What is a memory leak? How can it be avoided?

Answer: A memory leak occurs when dynamically allocated memory is not deallocated, leading to wasted memory. Example:
int* ptr = new int(10);  // Memory allocated
// No delete → memory leak
How to avoid:
  • Always use delete after new.
  • Use smart pointers (std::unique_ptr, std::shared_ptr).
  • Use tools like Valgrind for leak detection.

44. What is a smart pointer? Types of smart pointers in C++11?

Answer: Smart pointers are class templates that automatically manage the lifetime of dynamically allocated objects. Types in C++11:
  1. std::unique_ptr – Sole ownership.
  2. std::shared_ptr – Shared ownership.
  3. std::weak_ptr – Non-owning reference to shared_ptr.

45. What is the use of std::shared_ptr and std::unique_ptr?

Answer:
Smart Pointer Description

Ownership

std::unique_ptr Manages memory exclusively. Only one owner.
std::shared_ptr Reference counted shared ownership. Multiple owners.
Example:
#include <memory>
std::unique_ptr<int> uptr(new int(5));
std::shared_ptr<int> sptr1 = std::make_shared<int>(10);
std::shared_ptr<int> sptr2 = sptr1;  // shared ownership

46. What is a null pointer and dangling pointer?

Answer:
  • Null Pointer: Points to nothing (nullptr or NULL).
int* p = nullptr;
  • Dangling Pointer: Points to freed or invalid memory.
int* p = new int(5);
delete p;
// p is now dangling unless set to nullptr
p = nullptr;

47. What is pointer arithmetic?

Answer: Pointer arithmetic involves operations like increment, decrement, addition, and subtraction on pointers. Example:
int arr[] = {10, 20, 30};
int* ptr = arr;
ptr++;  // Now points to 20
Notes:
  • Incrementing moves the pointer by sizeof(type).
  • Only valid within the array/object range.

48. What is the difference between * and & operators in C++?

Answer:

Operator

Meaning

Example

* Dereference (get value at address) *ptr = 5;
& Address-of (get address of variable) ptr = &x;
* works with pointers; & gives address.

49. How are arrays and pointers related?

Answer:
  • The name of the array is a pointer to its first element.
  • Arrays and pointers are closely related but not the same.
Example:
int arr[5] = {1, 2, 3, 4, 5};
int* ptr = arr;  // Points to arr[0]
cout << *(ptr + 2);  // 3
Note: sizeof(arr) gives size of whole array, sizeof(ptr) gives size of pointer.

50. What is the difference between shallow copy and deep copy in pointer usage?

Answer:

Copy Type

Shallow Copy

Deep Copy

Definition Copies pointer addresses Copies actual values to new memory
Risk Two pointers point to same data Safe and independent copies
Problem Changes in one affect the other Independent copies prevent side-effects
Example:
class Test {
    int* data;
public:
    Test(int val) { data = new int(val); }
    // Deep Copy
    Test(const Test& t) {
        data = new int(*t.data);
    }
    ~Test() { delete data; }
};

51. What is the Standard Template Library (STL) in C++?

Answer: The Standard Template Library (STL) is a powerful set of C++ template classes that provides generic containers, algorithms, iterators, and function objects. It enables reusable, efficient, and type-safe code with compile-time type checking.

52. What are the main components of STL?

Answer: STL consists of four main components:
  1. Containers → Store data (vector, list, map, etc.)
  2. Algorithms → Operate on containers (sort, find, count, etc.)
  3. Iterators → Access container elements (begin(), end(), etc.)
  4. Function Objects (Functors) → Used in custom operations in algorithms

53. What is the difference between vector, list, and deque?

Answer:
Feature vector list (doubly linked)

deque

Memory Layout Contiguous Non-contiguous (nodes) Segmented
Insertion Fast at end Fast at both ends & middle Fast at both ends
Random Access Yes (O(1)) No (O(n)) Yes (O(1))
Overhead Less More (pointers) More (slightly higher than vector)
Use vector for random access, list for frequent insertions/deletions, and deque for double-ended queues.

54. How is a map different from unordered_map?

Answer:

Feature

map

unordered_map

Order Sorted (by key) Unordered
Implementation Balanced BST (Red-Black Tree) Hash Table
Time Complexity O(log n) O(1) average, O(n) worst
Key Comparison Uses operator< Uses hash and equality functions
Use unordered_map for fast access, and map when order matters.

55. What are iterators in STL?

Answer: Iterators are objects that point to elements in containers and enable traversal using a pointer-like interface. Common Types:
  • begin(), end(), rbegin(), rend()
  • Input, Output, Forward, Bidirectional, Random Access
Example:
vector<int> v = {1, 2, 3};
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << " ";

56. What is the use of lambda expressions in C++11?

Answer: Lambda expressions are anonymous functions that can be defined inline and passed to STL algorithms. Syntax:
[ capture ] (parameters) -> return_type { body }
Example:
vector<int> v = {1, 2, 3, 4, 5};
int evenCount = count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
Lambdas make code concise and enable custom logic in-place.

57. What are functors in C++?

Answer: A functor (function object) is a class or struct that overloads the operator(), making its objects callable like functions. Example:
struct MultiplyBy2 {
    int operator()(int x) const {
        return x * 2;
    }
};
MultiplyBy2 fn;
cout << fn(10);  // Output: 20
Used in STL algorithms like sort(), for_each() etc., as custom comparators or predicates.

58. What is the difference between std::sort() and qsort()?

Answer:

Feature

std::sort()

qsort() (C-style)

Language C++ (template-based) C
Type Safety Yes No (uses void* and function ptrs)
Performance Faster (inline, optimized) Slower (no inlining, overhead)
Usage Works with iterators and functors Works with pointers and structs
Prefer std::sort() in C++ for safety, performance, and cleaner code.

59. What is exception handling in C++? How do try, catch, and throw work?

Answer: Exception Handling in C++ is used to handle runtime errors gracefully without crashing the program. Keywords:
  • try → Block of code to monitor for errors
  • throw → Used to raise (throw) an exception
  • catch → Block to handle the thrown exception
Example:
try {
    int x = 0;
    if (x == 0)
        throw "Division by zero error!";
} catch (const char* msg) {
    cout << msg << endl;
}

60. What is RAII (Resource Acquisition Is Initialization) in C++?

RAII is a programming idiom where resource allocation (memory, file, lock, etc.) is tied to object lifetime. Key Points:
  • Resources are acquired in constructor
  • Released in destructor automatically
  • Prevents memory leaks and dangling handles
Example:
class FileHandler {
    FILE* file;
public:
    FileHandler(const char* filename) {
        file = fopen(filename, "r");
    }
    ~FileHandler() {
        fclose(file);  // Automatic cleanup
    }
};
Modern C++ uses RAII in std::unique_ptr, std::lock_guard, etc.
Note: The interview questions and answers provided on this page have been thoughtfully compiled by our academic team. However, as the content is manually created, there may be occasional errors or omissions. If you have any questions or identify any inaccuracies, please contact us at team@learn2earnlabs.com. We appreciate your feedback and strive for continuous improvement.