Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

C++ Interview Questions

C++

Top 25 C++ Interview Questions

Curated questions covering OOP, STL, smart pointers, move semantics, templates, and modern C++17/20 features.

01

What are the main OOP concepts supported by C++?

  • Encapsulation — data and methods bundled in a class; access controlled via public/private/protected.
  • Inheritance — a derived class inherits members from a base class.
  • Polymorphism — same interface, different behaviour; achieved via virtual functions (runtime) and function overloading (compile-time).
  • Abstraction — hiding implementation details via abstract classes and interfaces.
02

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

The only difference is the default access specifier: struct members are public by default; class members are private by default. Both support inheritance, methods, and constructors.

03

What are constructors and destructors in C++?

A constructor initialises an object when it is created. A destructor cleans up resources when the object goes out of scope or is deleted. Destructors are called in reverse order of construction.

Example
class Resource {
public:
    Resource()  { std::cout << "Constructed\n"; }
    ~Resource() { std::cout << "Destroyed\n"; }
};
{
    Resource r; // Constructed
} // Destroyed — destructor called automatically
04

What are the types of inheritance in C++?

  • Single — one derived class inherits from one base class.
  • Multiple — a class inherits from more than one base class.
  • Multilevel — a class inherits from a derived class (chain).
  • Hierarchical — multiple classes inherit from a single base class.
  • Hybrid — combination of two or more types of inheritance.
05

What are virtual functions and why are they used?

A virtual function is declared with the virtual keyword in a base class and overridden in derived classes. It enables runtime polymorphism — the correct function is called based on the actual object type, not the pointer/reference type.

Example
class Animal {
public:
    virtual void speak() { std::cout << "..."; }
};
class Dog : public Animal {
public:
    void speak() override { std::cout << "Woof!"; }
};
Animal *a = new Dog();
a->speak(); // "Woof!" — runtime dispatch
06

What is an abstract class in C++?

An abstract class has at least one pure virtual function (= 0). It cannot be instantiated directly and must be subclassed with all pure virtual functions implemented.

Example
class Shape {
public:
    virtual double area() = 0; // pure virtual
};
class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() override { return 3.14159 * r * r; }
};
07

What are templates in C++?

Templates allow writing generic code that works with any data type. Function templates and class templates are instantiated by the compiler for each type used.

Example
template &lt;typename T&gt;
T maxVal(T a, T b) { return (a > b) ? a : b; }

std::cout &lt;&lt; maxVal(3, 7);       // 7 (int)
std::cout &lt;&lt; maxVal(3.5, 2.1);   // 3.5 (double)
08

What is the STL and what are its main components?

  • Containers — store data: vector, list, deque, set, map, unordered_map, stack, queue.
  • Iterators — provide a uniform way to traverse containers.
  • Algorithms — generic algorithms: sort, find, count, transform, accumulate.
  • Function objects (functors) — objects that behave like functions.
Example
#include &lt;vector&gt;
#include &lt;algorithm&gt;
std::vector&lt;int&gt; v = {5, 2, 8, 1, 9};
std::sort(v.begin(), v.end());
// v = {1, 2, 5, 8, 9}
09

What are smart pointers in C++?

  • unique_ptr — sole ownership; automatically deleted when out of scope; cannot be copied.
  • shared_ptr — shared ownership via reference counting; deleted when last owner is destroyed.
  • weak_ptr — non-owning reference to a shared_ptr; breaks circular references.
Example
#include &lt;memory&gt;
auto up = std::make_unique&lt;int&gt;(42);
auto sp = std::make_shared&lt;int&gt;(10);
std::weak_ptr&lt;int&gt; wp = sp;
std::cout &lt;&lt; *up; // 42
std::cout &lt;&lt; *sp; // 10
10

What is RAII (Resource Acquisition Is Initialisation)?

RAII is a C++ idiom where resource acquisition (memory, file handles, locks) is tied to object lifetime. Resources are acquired in the constructor and released in the destructor, ensuring cleanup even when exceptions occur. Smart pointers and std::lock_guard are classic RAII examples.

11

What is move semantics in C++11?

Move semantics allow transferring resources from a temporary (rvalue) object instead of copying them, avoiding expensive deep copies. std::move() casts an lvalue to an rvalue reference.

Example
std::vector&lt;int&gt; a = {1, 2, 3};
std::vector&lt;int&gt; b = std::move(a); // a is now empty
// b owns the data; no copy was made
12

What are lambda expressions in C++?

Lambdas are anonymous inline functions. They can capture variables from the enclosing scope by value [=] or by reference [&].

Example
auto add = [](int a, int b) { return a + b; };
std::cout &lt;&lt; add(3, 4); // 7

int x = 10;
auto addX = [x](int n) { return n + x; }; // capture by value
std::cout &lt;&lt; addX(5); // 15
13

What is the auto keyword in C++11?

auto lets the compiler deduce the type of a variable from its initialiser. It reduces verbosity, especially with complex iterator types.

Example
auto x = 42;          // int
auto pi = 3.14;       // double
auto it = v.begin();  // std::vector&lt;int&gt;::iterator
for (auto& elem : v) { elem *= 2; }
14

What is range-based for loop in C++11?

Range-based for provides a cleaner syntax for iterating over containers and arrays without managing iterators manually.

Example
std::vector&lt;int&gt; nums = {1, 2, 3, 4, 5};
for (int n : nums) {
    std::cout &lt;&lt; n &lt;&lt; " ";
}
// Use auto& to modify elements
for (auto& n : nums) { n *= 2; }
15

What is exception handling in C++?

C++ uses try/catch/throw for exception handling. Exceptions can be any type, but std::exception subclasses are conventional. The noexcept specifier indicates a function will not throw.

Example
try {
    if (x == 0) throw std::runtime_error("Division by zero");
    int result = 10 / x;
} catch (const std::runtime_error& e) {
    std::cerr &lt;&lt; "Error: " &lt;&lt; e.what();
} catch (...) {
    std::cerr &lt;&lt; "Unknown error";
}
16

What are namespaces in C++?

Namespaces prevent name collisions by grouping identifiers under a named scope. The standard library uses the std namespace.

Example
namespace Math {
    double PI = 3.14159;
    double square(double x) { return x * x; }
}
std::cout &lt;&lt; Math::PI;
std::cout &lt;&lt; Math::square(4); // 16
17

What is operator overloading in C++?

Operator overloading allows defining custom behaviour for operators (+, -, ==, etc.) when applied to user-defined types.

Example
class Vector2D {
public:
    float x, y;
    Vector2D operator+(const Vector2D& o) const {
        return {x + o.x, y + o.y};
    }
};
Vector2D a{1,2}, b{3,4};
Vector2D c = a + b; // {4, 6}
18

What is a friend function in C++?

A friend function is declared inside a class with the friend keyword but defined outside. It has access to the class's private and protected members without being a member itself.

19

What is the diamond problem in multiple inheritance?

The diamond problem occurs when a class inherits from two classes that both inherit from a common base, creating ambiguity about which base class copy to use. C++ solves this with virtual inheritance.

Example
class A { public: int x; };
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
// D has only one copy of A::x
20

What is the copy constructor and when is it called?

A copy constructor creates a new object as a copy of an existing object. It is called when an object is passed by value, returned by value, or explicitly copied.

Example
class MyClass {
public:
    int* data;
    MyClass(const MyClass& other) { // copy constructor
        data = new int(*other.data); // deep copy
    }
};
21

What is the Rule of Three/Five in C++?

  • Rule of Three — if you define any of: destructor, copy constructor, copy assignment operator, you should define all three.
  • Rule of Five (C++11) — extends Rule of Three to include move constructor and move assignment operator.
  • Rule of Zero — prefer using RAII types (smart pointers, containers) so you need none of the five.
22

What are C++17 structured bindings?

Structured bindings allow decomposing a tuple, pair, or struct into named variables in a single declaration.

Example
std::map&lt;std::string, int&gt; scores = {{"Alice", 95}, {"Bob", 87}};
for (auto& [name, score] : scores) {
    std::cout &lt;&lt; name &lt;&lt; ": " &lt;&lt; score &lt;&lt; "\n";
}
23

What is std::optional in C++17?

std::optional represents a value that may or may not be present, avoiding the use of null pointers or sentinel values.

Example
#include &lt;optional&gt;
std::optional&lt;int&gt; findAge(bool found) {
    if (found) return 25;
    return std::nullopt;
}
auto age = findAge(true);
if (age) std::cout &lt;&lt; *age; // 25
24

What are C++20 concepts?

Concepts constrain template parameters, providing clearer error messages and better documentation of template requirements.

Example
#include &lt;concepts&gt;
template &lt;typename T&gt;
requires std::integral&lt;T&gt;
T square(T x) { return x * x; }

square(5);    // OK
// square(3.14); // compile error — not integral
25

What is the difference between stack and heap allocation in C++?

  • Stack — automatic storage; fast allocation/deallocation; limited size; objects destroyed when scope ends.
  • Heap — dynamic storage via new/delete or smart pointers; larger; manual or RAII-managed lifetime.
  • Prefer stack allocation and RAII wrappers over raw new/delete.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.