Interview Preparation

C++ Interview Questions

Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.

29
Questions
100%
Expert Answers
Q1
What is C++? What are the advantages of C++?

C++ is an object-oriented programming language developed as an extension of the C language. It was introduced to overcome the limitations of the C language by incorporating object-oriented features such as classes, objects, polymorphism, inheritance, abstraction, and encapsulation.

C++ offers several advantages:

  • Object-Oriented Programming (OOP): C++ treats data as objects, promoting modular and reusable code through the use of OOP principles.
  • Multi-Paradigm Support: C++ supports multiple programming paradigms, including procedural, object-oriented, and generic programming, allowing flexibility in how software is designed and structured.
  • Efficient Memory Management: C++ provides dynamic memory allocation and deallocation using pointers and operators like new and delete, giving developers fine-grained control over system resources.
  • Mid-Level Language: C++ combines high-level features for application development and low-level capabilities for system programming, making it suitable for building games, operating systems, desktop applications, drivers, and kernels.
Q2
Define 'std'?

std stands for 'standard' and is the namespace used by the C++ Standard Library. It contains all the built-in functions, objects, and classes provided by the standard library, such as cout, cin, vector, string, and many more.

To avoid writing std:: repeatedly before standard library components, we often use the directive using namespace std;. This tells the compiler to use the 'std' namespace globally within the program so that we can directly use components like cout and cin without the std:: prefix.

For example:

#include <iostream>
using namespace std;

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

While using namespace std; simplifies code, it's generally discouraged in large projects or header files because it can lead to name conflicts.

Q3
Define token in C++

In C++, a token is the smallest individual element of a program that the compiler can understand and process. Tokens are the basic building blocks of a C++ program and are categorized into various types.

Types of Tokens in C++:

  • Keywords: These are reserved words that have special meanings defined by the C++ language, such as int, return, if, else, etc.
  • Identifiers: Names given to variables, functions, arrays, etc., to uniquely identify them in the program.
  • Constants: Fixed values that do not change during the execution of a program, such as numeric or character constants.
  • Strings: A sequence of characters enclosed in double quotes, used to represent textual data.
  • Special Symbols: Characters with specific meaning in C++, like [], (), {}, ;, *, =, and #.
  • Operators: Symbols that perform operations on variables and values, such as +, -, *, /, etc.

Understanding tokens is fundamental to writing syntactically correct C++ programs, as every statement is composed of one or more tokens.

Q4
What is the difference between struct and class?

In C++, both struct and class can be used to define user-defined data types. They are nearly identical in functionality, but there are some key differences primarily in their default access modifiers and common use cases.

Difference between struct and class:

Aspectstructclass
Default Access ModifierMembers are public by default.Members are private by default.
Memory AllocationCan be allocated on the stack or heap.Can be allocated on the stack or heap.
InheritanceSupports inheritance (with public, protected, or private access).Supports inheritance (with public, protected, or private access).
Use CaseOften used for Plain Old Data (POD) structures, or simple data grouping.Suitable for complex objects that may include methods, constructors, and destructors.
Q5
What is the difference between reference and pointer?

In C++, both references and pointers are used to refer to other variables. However, they behave differently and serve different purposes. Below is a comparison that outlines the key differences between them.

ReferencePointer
The value of a reference cannot be reassigned.The value of a pointer can be reassigned to point to a different variable.
It can never hold a null value; it must be initialized when declared.It can hold or point to a null value and be referred to as a nullptr.
Uses dot (.) operator to access class/struct members.Uses arrow (->) operator to access class/struct members.
Memory address can be accessed directly like a normal variable.Requires dereferencing with * operator to access memory.
Q6
What is the difference between function overloading and operator overloading?

In C++, both function overloading and operator overloading are forms of polymorphism, allowing developers to use the same name or operator in different ways. However, they serve different purposes. The key differences are given below:

Function OverloadingOperator Overloading
Allows multiple functions to have the same name with different parameter lists.Allows redefining the meaning of existing operators for user-defined types (objects).
Used to perform different tasks using the same function name based on input types or number of parameters.Used to perform operations on objects using conventional operators like +, -, *, etc., by overloading them.
Example:
int add(int a, int b);
double add(double a, double b);
string add(string a, string b);
Example:
class Complex {
  int real, imag;
  public:
    Complex operator+(const Complex& obj) {
      Complex res;
      res.real = real + obj.real;
      res.imag = imag + obj.imag;
      return res;
    }
};
Q7
What is 'this' pointer in C++?

In C++, the this pointer is an implicit pointer available to all non-static member functions. It points to the current object — that is, the object for which the member function was called.

The this pointer is primarily used when:

  • We need to return the object itself from a method (to support method chaining).
  • We want to pass the current object as a parameter to another function.
  • There is a naming conflict between instance variables and parameters or local variables — this-> helps distinguish them.

Example:

class Student {
  int id;
public:
  void setId(int id) {
    this->id = id;  // 'this' differentiates between the member and parameter
  }

  Student* getPointer() {
    return this;  // returns pointer to the current object
  }
};

Thus, the this pointer provides access to the invoking object and helps manage object-oriented behavior effectively in C++ programs.

Q8
What is the difference between new and malloc()?

In C++, both new and malloc() are used for dynamic memory allocation, but they have significant differences in how they operate and are used.

newmalloc()
It is an operator used in C++ for dynamic memory allocation.It is a library function in C that allocates memory dynamically.
It calls the constructor of the object being created.It does not call any constructor; it only allocates raw memory.
It returns a pointer of the correct data type.It returns a void* pointer which needs to be explicitly typecasted.
It is generally faster as it is an operator with built-in support in C++.It is slower in comparison because it is a function call.
Q9
What is the difference between virtual functions and pure virtual functions?

In C++, virtual functions and pure virtual functions are used to achieve polymorphism, but they differ in their implementation and purpose.

Virtual FunctionPure Virtual Function
A virtual function is a member function of a base class that can be redefined in its derived class.A pure virtual function is a member function of a base class that is declared but not defined in the base class and must be defined in a derived class.
It has a body (definition) in the base class and can optionally be overridden in derived classes.It has no definition in the base class and is assigned with = 0 making the class abstract.
A class with virtual functions can be instantiated and used to create objects.A class with at least one pure virtual function becomes an abstract class and cannot be instantiated.
Q10
What are the various OOPs concepts in C++?

C++ is a powerful object-oriented programming language that allows developers to model real-world problems more intuitively using objects and classes. The language provides several core OOP concepts that serve as building blocks for software design and development. These concepts include:

1. Class:

A class is a user-defined blueprint or prototype from which objects are created. It groups data members (variables) and member functions (methods) that operate on the data. It defines the properties and behavior of an object.

class Car {
    public:
        string brand;
        void start() {
            cout << "Car Started";
        }
};

2. Object:

An object is an instance of a class. It represents a real-world entity and has its own identity, state, and behavior. Objects use class definitions to access data and perform operations.

Car myCar;
myCar.brand = "Tesla";
myCar.start();

3. Encapsulation:

Encapsulation is the practice of wrapping data and methods into a single unit (class) and restricting direct access to some components. It helps protect object integrity by preventing unintended interference and misuse of internal data.

class Account {
    private:
        double balance;
    public:
        void deposit(double amount) {
            balance += amount;
        }
};

4. Abstraction:

Abstraction is the concept of hiding the internal details and showing only the functionality to the user. It reduces complexity by exposing only relevant data and behavior through interfaces or abstract classes.

5. Inheritance:

Inheritance allows a class (child or derived class) to inherit attributes and methods from another class (base or parent class). It promotes code reuse and establishes a hierarchical relationship between classes.

class Vehicle {
    public:
        void drive() {
            cout << "Driving";
        }
};

class Car : public Vehicle {
    // Inherits drive() from Vehicle
};

6. Polymorphism:

Polymorphism means 'many forms.' It allows functions and operators to behave differently based on the context. There are two types:

  • Compile-time Polymorphism (Function Overloading, Operator Overloading)
  • Run-time Polymorphism (Function Overriding using virtual functions)
// Compile-time
int add(int a, int b);
double add(double a, double b);

// Run-time
class Animal {
    public:
        virtual void sound() { cout << "Animal sound"; }
};
class Dog : public Animal {
    public:
        void sound() override { cout << "Bark"; }
};

7. Constructor and Destructor:

Constructors are special functions automatically called when an object is created, used to initialize data members. Destructors are called when an object is destroyed, used for cleanup tasks such as releasing memory.

class Box {
    public:
        Box() { cout << "Constructor called"; }
        ~Box() { cout << "Destructor called"; }
};

These concepts form the foundation of OOP in C++, making it easier to develop structured, scalable, and maintainable software applications.

Q11
What is Function Overriding?

Function Overriding in C++ occurs when a derived class defines a function with the same name, return type, and parameters as a function already declared in its base class. The derived class's version of the function overrides the base class's version.

This is an example of Runtime Polymorphism (also known as Late Binding), meaning the decision about which function to execute is made at runtime rather than compile-time. To enable overriding, the function in the base class is typically marked with the virtual keyword.

Function overriding allows dynamic behavior, enabling derived classes to provide specific implementations for functions defined in their base class, especially when accessed through pointers or references to the base class.

Q12
When should we use multiple inheritance?

Multiple inheritance in C++ refers to the capability of a class (known as the derived class) to inherit from more than one base class. This feature becomes useful when a derived class needs to combine behaviors, attributes, or interfaces from multiple classes to fulfill its purpose.

We should use multiple inheritance when:

  • A class needs to inherit and reuse functionality from more than one parent class.
  • Different base classes define logically separate roles or capabilities that a single class must combine.
  • You want to build composite classes from small, reusable components (mixins).

Real-Life Analogy:

Consider a real-life example: you are a child who inherits characteristics from both your father and your mother. In programming terms, the child class inherits from two base classes: Dad and Mom. This is a form of multiple inheritance where the child gets attributes or behavior from both parents.

Example:

class Dad {
public:
    void skillA() { cout << "Driving"; }
};

class Mom {
public:
    void skillB() { cout << "Cooking"; }
};

class Child : public Dad, public Mom {
    // Inherits both skillA and skillB
};

int main() {
    Child obj;
    obj.skillA(); // Output: Driving
    obj.skillB(); // Output: Cooking
}

However, multiple inheritance should be used with caution due to potential issues such as the diamond problem, where the same base class may be inherited multiple times through different paths. To resolve such conflicts, C++ supports virtual inheritance.

Q13
What is virtual inheritance?

Virtual inheritance is a technique in C++ that ensures only one instance of a base class's member variables is inherited, even if multiple derived classes inherit from the same base class. This technique is primarily used to resolve the diamond problem in multiple inheritance scenarios.

Why is Virtual Inheritance Needed?

Consider a situation where two classes inherit from the same base class, and a fourth class inherits from those two classes. Without virtual inheritance, the fourth class will end up with two copies of the base class, leading to ambiguity and redundancy.

Example without Virtual Inheritance (Diamond Problem):

class A {
public:
    int value;
};

class B : public A { };
class C : public A { };

class D : public B, public C {
    // Ambiguous: which 'value' to use from A?
};

Solution using Virtual Inheritance:

class A {
public:
    int value;
};

class B : virtual public A { };
class C : virtual public A { };

class D : public B, public C {
    // No ambiguity: single shared instance of A
};

Conclusion: Virtual inheritance is useful when building complex class hierarchies with multiple inheritance, as it avoids the duplication of base class instances and prevents ambiguity in the derived classes.

Q14
What is polymorphism in C++? What are its different types?

Polymorphism in C++ refers to the ability of a function, operator, or object to behave in different ways based on the context. The term comes from Greek, meaning "many forms." In programming, polymorphism allows the same interface to be used for different underlying data types or behaviors.

Real-life Analogy: A person can be a father to his child, an employee to his company, and a son to his parents — all at the same time. The role changes depending on the context. This is how polymorphism works in programming.

There are two main types of polymorphism in C++:

1️. Compile-Time Polymorphism (Static Binding)

This occurs when the function or operator is resolved at compile time. It does not require inheritance.

  • Function Overloading: When multiple functions share the same name but differ in parameters (type or number).
int add(int a, int b);      // two int params
float add(float a);        // one float param
int add(int a, int b, int c); // three int params
  • Operator Overloading: Redefining the behavior of operators (like +, -, ==) for user-defined types (classes).
class Point {
    int x, y;
public:
    Point(int a, int b) : x(a), y(b) {}
    Point operator + (const Point& p) {
        return Point(x + p.x, y + p.y);
    }
};

2️. Run-Time Polymorphism (Dynamic Binding)

This type of polymorphism occurs when a function call is resolved at runtime using inheritance and virtual functions.

  • Function Overriding: A derived class provides a specific implementation of a function already defined in its base class.
#include <iostream>
using namespace std;

class Animal {
public:
    virtual void speak() {
        cout << "Animal speaks" << endl;
    }
};

class Dog : public Animal {
public:
    void speak() override {
        cout << "Dog barks" << endl;
    }
};

int main() {
    Animal* a;
    Dog d;
    a = &d;
    a->speak();  // Output: Dog barks
    return 0;
}

Conclusion: Polymorphism in C++ increases flexibility, extensibility, and reusability of code by allowing functions and objects to behave differently based on the situation. It is a fundamental concept in object-oriented programming.

Q15
Explain constructors and destructors in C++

In C++, constructors and destructors are special member functions of a class that handle the initialization and cleanup of objects respectively. They ensure proper object lifecycle management, and both share the name of the class, with destructors being prefixed by a tilde (~).

Constructor

A constructor is a special type of member function that is automatically called when an object is created. It has the same name as the class and is used to initialize object properties. There are three main types of constructors:

1. Default Constructor: A constructor that takes no arguments. It is either defined explicitly by the programmer or implicitly provided by the compiler.

class MyClass {
public:
    MyClass() {
        cout << "Default constructor called";
    }
};

2. Parameterized Constructor: This constructor takes arguments, allowing different values to be assigned at the time of object creation. It also supports constructor overloading.

#include <iostream>
using namespace std;

class Point {
private:
    int x, y;

public:
    Point(int a, int b) {
        x = a;
        y = b;
    }

    int getX() { return x; }
    int getY() { return y; }
};

int main() {
    Point p(10, 15);
    cout << "X = " << p.getX() << ", Y = " << p.getY();
    return 0;
}

3. Copy Constructor: This constructor initializes a new object as a copy of an existing object. It takes a reference to an object of the same class as its parameter.

class Sample {
    int id;
public:
    Sample(int val) { id = val; }
    Sample(const Sample &obj) { id = obj.id; }
};

Destructor

A destructor is a special member function that is automatically called when an object goes out of scope or is deleted. It is used to free resources that the object may have acquired during its lifetime. A destructor has the same name as the class, preceded by a tilde (~), and it does not take any arguments or return any value.

class MyClass {
public:
    ~MyClass() {
        cout << "Destructor called";
    }
};

While constructors are executed from top to bottom when objects are created, destructors follow a bottom-to-top order when objects are destroyed. This ensures that resources are released in the reverse order they were acquired.

Q16
What is a virtual destructor?

A virtual destructor in C++ ensures that the correct destructor is called for an object when it is deleted through a pointer to the base class. It is especially important when using inheritance and polymorphism, as it allows proper cleanup of both the derived and base class resources.

Without a virtual destructor, deleting a derived class object through a base class pointer may lead to undefined behavior and memory leaks because only the base class's destructor will be called, skipping the derived class cleanup.

It is a best practice to declare destructors as virtual when your class is intended to be used as a base class and has virtual functions.

Example:

#include <iostream>
using namespace std;

class Base {
public:
    virtual ~Base() {
        cout << "Base class destructor called" << endl;
    }
};

class Derived : public Base {
public:
    ~Derived() {
        cout << "Derived class destructor called" << endl;
    }
};

int main() {
    Base* obj = new Derived();
    delete obj;
    return 0;
}

Output:
Derived class destructor called
Base class destructor called

In this example, the use of virtual ensures both destructors run in the correct order, preventing memory leaks and undefined behavior.

Q17
Is destructor overloading possible? If yes then explain and if no then why?

No, destructor overloading is not possible in C++. A class can only have one destructor, and it cannot be overloaded. This is because a destructor is a special member function that does not take any parameters and does not return any value, so there is no way to differentiate between multiple destructors based on parameters as we do with overloaded functions or constructors.

The purpose of a destructor is to perform clean-up operations when an object goes out of scope or is explicitly deleted. Since destructors do not accept arguments, there is no flexibility to create variations of it. Hence, C++ strictly allows only a single destructor per class.

Attempting to declare more than one destructor in a class results in a compilation error.

Example (Invalid Code):

class Example {
public:
    ~Example() { }
    // Error: destructor overloading is not allowed
    ~Example(int x) { } // ❌ Invalid
};

As shown above, trying to define a destructor with parameters will result in an error, confirming that destructor overloading is not supported in C++.

Q18
Which operations are permitted on pointers?

Pointers are special variables in C++ used to store the memory address of other variables. Several operations are permitted on pointers that allow manipulation of the memory address they hold. These operations are essential in pointer arithmetic, iteration, and memory management.

1. Increment/Decrement of a Pointer:

You can increment (++) or decrement (--) a pointer to move to the next or previous memory location of its type. For example, if a pointer points to an integer, incrementing it moves it to the next integer-sized memory block.

int arr[] = {10, 20, 30};
int* ptr = arr;
ptr++;  // Now points to arr[1]

2. Addition and Subtraction of Integer to a Pointer:

You can add or subtract an integer from a pointer. This adjusts the pointer to point to another memory location relative to its current address.

int* ptr = arr;
ptr = ptr + 2;  // Now points to arr[2]

3. Comparison of Pointers of the Same Type:

Pointers that point to elements of the same array or same type can be compared using relational operators such as ==, !=, <, >, etc.

if (ptr1 == ptr2) {
    cout << "Pointers point to the same location";
}

These operations provide flexibility when dealing with arrays, dynamic memory, and data structures like linked lists or trees.

Q19
How delete[] is different from delete?
delete[] delete
It is used for deleting a whole array It is used to delete only one single pointer
It is used for deleting the objects of new[]; By this, we can say that delete[] is used to delete an array of objects It is used for deleting the objects of new; By this, we can say that delete is used to delete a single object
It can call as many destructors as needed It can only call the destructor of a class once
Q20
What do you know about friend class and friend function?

Friend Class: A friend class in C++ is a class that is granted access to the private and protected members of another class. This means the friend class can directly access the internals of the class that declares it as a friend. It is declared using the friend keyword within the class that is granting access.

class ClassA {
    friend class ClassB; // ClassB is a friend of ClassA
private:
    int secret = 42;
};

class ClassB {
public:
    void showSecret(ClassA& obj) {
        std::cout << "Secret: " << obj.secret << std::endl;
    }
};

Friend Function: A friend function in C++ is a function that is not a member of a class but has the right to access all its private and protected members. It is also declared using the friend keyword. A friend function is often used when two or more classes need to share information or work closely together.

class Sample {
private:
    int value;
public:
    Sample(int v) : value(v) {}
    friend void printValue(Sample s);
};

void printValue(Sample s) {
    std::cout << "Value: " << s.value << std::endl;
}

Note: Friend functions are not called using an object of the class. They are called like regular functions but still have access to private and protected data of the class where they are declared as a friend.

Q21
What is an Overflow Error?

Overflow Error occurs when a numerical value exceeds the maximum limit that a particular data type can store. It is a common type of error that happens during arithmetic operations when the result is too large for the defined storage size.

For example, the range of the int data type in C++ is from –2,147,483,648 to 2,147,483,647. If you attempt to store a value like 2,247,483,648 in an int variable, it will result in an overflow error because the value exceeds the maximum range the int type can represent.

Such errors can lead to unpredictable program behavior, and in some cases, the values may wrap around to the negative side of the range.

#include <iostream>
using namespace std;

int main() {
    int x = 2147483647; // Max value for int
    x = x + 1; // Causes overflow
    cout << "Value of x: " << x << endl;
    return 0;
}
Q22
What does the Scope Resolution operator do?

The Scope Resolution Operator in C++ is denoted by ::. It is used to access a global variable when there is a local variable with the same name, to define a function outside the class, or to resolve ambiguity in cases like multiple inheritance or namespaces.

It helps reference identifiers that are not in the current scope, making it a powerful tool to manage variable and function scope efficiently.

Common Use Cases:

  • To access a global variable when a local variable with the same name exists
  • To define a class method outside the class definition
  • To resolve ambiguity in multiple inheritance scenarios
  • To specify members within a namespace
#include <iostream>
using namespace std;

int value = 100; // Global variable

int main() {
    int value = 50; // Local variable
    cout << "Local value: " << value << endl;
    cout << "Global value: " << ::value << endl; // Using scope resolution operator
    return 0;
}
Q23
What is STL?

STL stands for Standard Template Library. It is a powerful library in C++ that provides four key components: containers, algorithms, iterators, and function objects (functors). STL allows for the reuse of well-tested code and simplifies the implementation of common data structures and operations.

Here is a breakdown of STL components:

C++ STL
 ├── Algorithms
 │    ├── Binary
 │    ├── Lower/Upper Bound
 │    ├── Min/Max
 │    └── Reverse/Rotate → Sort/Scoop
 ├── Containers
 │    ├── Sequence Containers
 │    │    ├── Array
 │    │    ├── Vector
 │    │    ├── Deque
 │    │    └── List
 │    ├── Container Adapters
 │    │    ├── Stack
 │    │    ├── Queue
 │    │    └── Priority Queue
 │    ├── Associative Containers
 │    │    ├── Set
 │    │    └── Map
 │    └── Unordered Associative
 │        ├── Unordered Set
 │        └── Unordered Map

STL provides flexibility, type-safety, performance, and generic programming capabilities to C++ developers.

Q24
What are the static data members and static member functions?

Static Data Members:
A static data member of a class is a normal data member but is preceded with the static keyword. It is initialized only once and is shared across all objects of the class. It exists even if no object of the class is created, and its lifetime is throughout the program. Static members are typically used to keep track of values that should be shared among all instances.

Syntax:

static Data_Type Data_Member;
    

Static Member Functions:
A static member function is a function that can access only static data members or call other static member functions. It is declared using the static keyword and can be called using either the class name or objects (though the class name is preferred).

Syntax:

ClassName::FunctionName(parameter);
    
Q25
What is the main use of the keyword “volatile”?

The volatile keyword in C++ is used to inform the compiler that a variable's value may be changed at any time—without any action being taken by the code the compiler finds nearby. This means the compiler should not optimize the code that accesses this variable, as its value might unexpectedly change during program execution.

Main Uses:

  • Memory-mapped hardware registers
  • Variables shared by multiple threads
  • Variables modified by an interrupt service routine or signal handler

Example:

volatile int sensorValue;
    

This tells the compiler not to cache sensorValue in a register and to always read its current value from memory.

Q26
Define storage class in C++ and name some

Storage Class:
In C++, a storage class defines the lifetime, scope, and visibility of a variable or function. It tells the compiler how the variable should be stored, how long it should exist, and who can access it.

Syntax:

storage_class data_type variable_name;
    

Types of Storage Classes in C++:

  • auto – Default storage class for local variables.
  • register – Suggests storing the variable in a CPU register.
  • static – Retains the value of a variable between function calls.
  • extern – Declares a variable that is defined elsewhere (outside the current file or scope).
  • mutable – Allows a class member to be modified even if the object is declared const.
Q27
Can we call a virtual function from a constructor?

Yes, you can call a virtual function from a constructor in C++. However, it is generally not recommended.

When a virtual function is called inside a constructor (or destructor), the version of the function that gets called is the one defined in the current class, not the overridden version in a derived class.

This is because, during the constructor execution of a base class, the object is not yet fully constructed as the derived part hasn't been initialized. So, the polymorphic behavior does not work in constructors.

Example:


#include <iostream>
using namespace std;

class Base {
public:
    Base() {
        cout << "Base Constructor" << endl;
        show(); // Virtual function called from constructor
    }
    virtual void show() {
        cout << "Base show()" << endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        cout << "Derived Constructor" << endl;
    }
    void show() override {
        cout << "Derived show()" << endl;
    }
};

int main() {
    Derived d;
    return 0;
}
    

Output:
Base Constructor
Base show()
Derived Constructor

Q28
What is a mutable storage class specifier? How can they be used?

The mutable storage class specifier in C++ is used to allow a particular data member of a class to be modified even if it is a part of an object that is declared as const. It can only be applied to non-static and non-const data members.

This is particularly useful when you want certain members (like cache or logging flags) to remain modifiable even in const functions or when the entire object is constant.

Syntax:


class Demo {
private:
    mutable int counter;

public:
    Demo() : counter(0) {}

    void incrementCounter() const {
        counter++;  // Allowed because counter is mutable
    }

    int getCounter() const {
        return counter;
    }
};
    

Usage:
Even though incrementCounter() is a const function, it can still modify counter because counter is declared as mutable.

Q29
What is the function of the keyword 'auto'?

The auto keyword in C++ allows the compiler to automatically deduce the type of a variable from its initializer. It simplifies the declaration of variables with complex types such as iterators, pointers, or lambda expressions. Instead of explicitly writing the data type, the programmer can use auto to let the compiler infer it.

This feature helps in improving code readability and reducing redundancy, especially when working with STL containers or templates.

Example:


#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Instead of writing std::vector<int>::iterator
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }

    return 0;
}
    

Why Choose Our Question Bank?

Get access to expertly crafted answers and comprehensive preparation materials

Complete Collection

Access all 29 carefully curated questions covering every aspect of C++ interviews

Expert Answers

Get detailed, professional answers crafted by industry experts with real-world experience

Instant Access

Start preparing immediately with instant access to all questions and answers after sign-up