Freshers C++ Interview Questions

What is C++?

C++ is a compiled, general purpose programming language created by Bjarne Stroustrup at Bell Labs. It started in 1979 as “C with Classes” and got the name C++ in 1983. It supports procedural, object oriented and generic programming, and it gives you control of the memory, so it is very fast.

It is used for games and game engines, browsers, operating systems, databases, trading systems and embedded devices. Check your compiler version with:

Terminal

$ g++ –version | head -1
g++ (GCC) 16.2.0

Read C++ Introduction.

What are the main features of C++?

  • Compiled and fast: machine code with almost no overhead.
  • Object oriented: classes, inheritance, polymorphism, encapsulation, abstraction.
  • Generic programming: templates and concepts.
  • STL: ready containers, iterators and algorithms.
  • Memory control: pointers, references, new and delete, and smart pointers.
  • RAII: resources are freed by destructors, with no garbage collector.
  • Operator overloading and function overloading.
  • Multi paradigm and portable across systems.

See C++ Features.

What is the difference between C and C++?

PointCC++
StyleProceduralProcedural, object oriented, generic
ClassesNoYes
OverloadingNoYes
ReferencesNoYes
Templates, exceptionsNoYes
Strings and containerschar arrays, own codestd::string, STL
Memorymalloc and freenew, delete, smart pointers
I/Oprintf, scanfcout, cin, print

This C code is not valid C++, because C++ does not convert void* automatically:

#include <stdlib.h>

int main() {
    int* p = malloc(sizeof(int));
    free(p);
}
Output

Bad.cpp: In function 'int main()':
Bad.cpp:4:20: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
4 | int* p = malloc(sizeof(int));
| ~~~~~~^~~~~~~~~~~~~
| |
| void*

See C++ vs C.

What are the different versions (standards) of C++?

StandardMain additions
C++98 / 03Templates, STL, exceptions, namespaces
C++11auto, lambdas, nullptr, move semantics, smart pointers, range for
C++14Generic lambdas, make_unique
C++17Structured bindings, optional, variant, string_view, filesystem
C++20Concepts, ranges, modules, coroutines, std::format
C++23std::print, std::expected

You choose the version with a compiler flag, like -std=c++23. A newer one (C++26) is in the approval process. See C++ History and Versions.

What is the use of #include in C++?

#include is a preprocessor command. Before the compiler runs, the preprocessor copies the content of the header file into your file. <iostream> declares std::cout, std::cin, std::cerr and std::endl.

#include <iostream>

int main() {
    std::cout << "Hello\n";          // output
    std::cerr << "Error stream\n";   // output for errors
}
Output

Hello
Error stream

< > is used for standard headers, and quotes "my.h" for your own files. See C++ Input and Output.

What is the difference between cout and printf in C++?

Pointstd::coutprintfstd::print (C++23)
LanguageC++CC++23
Type safeYesNoYes
FormatStream operators <<%d, %s codes{} placeholders
Custom typesWith operator<<NoWith std::formatter
#include <cstdio>
#include <iostream>
#include <print>

int main() {
    int n = 5;
    double d = 2.5;
    std::cout << "cout: " << n << " " << d << '\n';
    std::printf("printf: %d %.1f\n", n, d);
    std::println("print: {} {:.1f}", n, d);
}
Output

cout: 5 2.5
printf: 5 2.5
print: 5 2.5

With printf a wrong code like %s for an int compiles but can crash. See C++ Input and Output.

What is the difference between endl and \n in C++?

'\n' writes a new line character. std::endl writes it and also flushes the output buffer (forces the text to go out at once). The flush is slow when you print many lines.

#include <chrono>
#include <iostream>
#include <sstream>

int main() {
    std::ostringstream a, b;
    for (int i = 0; i < 3; i++) a << i << '\n';
    for (int i = 0; i < 3; i++) b << i << std::endl;
    std::cout << (a.str() == b.str()) << '\n';       // the same text
}
Output

1

Use '\n' in normal code. Use std::endl only when you really need the flush, for example before a crash log.

What is a namespace in C++? Why not use using namespace std?

A namespace is a named scope for functions, classes and variables. It avoids name clashes between libraries. The standard library is in std.

#include <iostream>

namespace a { int value() { return 1; } }
namespace b { int value() { return 2; } }

int main() {
    std::cout << a::value() << ' ' << b::value() << '\n';
}
Output

1 2

using namespace std; brings every name of std into your scope. In big programs a name like count or distance can clash with your own. It is OK in a small test, but never write it in a header file. Better: using std::cout; or the full std::. See C++ Namespaces.

What is the difference between a reference and a pointer in C++?

PointReferencePointer
Must be initializedYesNo
Can be nullNoYes
Can be changed to refer to another variableNoYes
UseLike a normal variableNeeds * and ->
SizeSame as the object (alias)Size of an address
#include <iostream>

int main() {
    int a = 1, b = 2;
    int& ref = a;
    int* ptr = &a;

    ref = 10;              // changes a
    *ptr += 5;             // changes a
    ptr = &b;              // a pointer can point somewhere else
    *ptr = 20;
    std::cout << a << ' ' << b << '\n';
}
Output

15 20

See References and Pointers.

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

In C++, struct and class are almost the same. Both can have methods, constructors and inheritance. The only differences are the default access (and the default inheritance type).

#include <iostream>

struct S { int x = 1; };           // x is public
class C { int x = 2; public: int get() const { return x; } };   // x is private

int main() {
    S s;
    C c;
    std::cout << s.x << ' ' << c.get() << '\n';
}
Output

1 2

By habit: use struct for simple data, and class for objects with rules (invariants) and behavior. See Classes and Objects.

What is a constructor in C++ and what are its types?

A constructor initializes an object. It has the same name as the class and no return type.

  • Default: no parameters.
  • Parameterized: takes values.
  • Copy: T(const T&), makes an object from another one.
  • Move: T(T&&), takes the data of a temporary.
  • Delegating: calls another constructor of the same class.
#include <iostream>
#include <string>

class P {
public:
    P() : P("none", 0) { std::cout << "default\n"; }
    P(std::string n, int a) : name(std::move(n)), age(a) { std::cout << "parameterized\n"; }
    P(const P& o) : name(o.name), age(o.age) { std::cout << "copy\n"; }
private:
    std::string name;
    int age;
};

int main() {
    P a;
    P b("Riya", 21);
    P c = b;
}
Output

parameterized
default
parameterized
copy

See Constructors and Destructors.

What is a destructor in C++?

A destructor is called automatically when an object goes out of scope or is deleted. It has no parameters and no return type. Use it to free what the object owns (memory, files, locks).

#include <iostream>

class File {
public:
    File()  { std::cout << "open\n"; }
    ~File() { std::cout << "close\n"; }
};

int main() {
    File a;
    {
        File b;
        std::cout << "inside block\n";
    }
    std::cout << "end of main\n";
}
Output

open
open
inside block
close
end of main
close

Objects are destroyed in the reverse order of their creation. See Constructors and Destructors.

What is function overloading in C++?

Many functions can share one name when their parameter lists are different (number or types). The compiler chooses the best match at compile time.

#include <iostream>
#include <string>

void show(int x)               { std::cout << "int " << x << '\n'; }
void show(double x)            { std::cout << "double " << x << '\n'; }
void show(const std::string& x) { std::cout << "string " << x << '\n'; }

int main() {
    show(5);
    show(2.5);
    show(std::string("hello"));
}
Output

int 5
double 2.5
string hello

See Function Overloading and Default Arguments.

What is the difference between overloading and overriding in C++?

PointOverloadingOverriding
WhereSame scopeBase and derived class
ParametersDifferentSame
Needs virtualNoYes (for run time behavior)
DecidedCompile timeRun time
#include <iostream>

struct Base {
    virtual void f() const { std::cout << "Base::f\n"; }
    void g(int) const { std::cout << "g(int)\n"; }
    void g(double) const { std::cout << "g(double)\n"; }       // overloading
};

struct Derived : Base {
    void f() const override { std::cout << "Derived::f\n"; }    // overriding
};

int main() {
    Derived d;
    const Base& b = d;
    b.f();
    b.g(1);
    b.g(1.5);
}
Output

Derived::f
g(int)
g(double)

See Polymorphism and Function Overloading.

What is a virtual function in C++?

A virtual function is chosen when the program runs, by the real type of the object. This is run time polymorphism.

#include <iostream>
#include <memory>

struct Animal {
    virtual ~Animal() = default;
    virtual void sound() const { std::cout << "...\n"; }
};
struct Dog : Animal { void sound() const override { std::cout << "Woof\n"; } };
struct Cat : Animal { void sound() const override { std::cout << "Meow\n"; } };

int main() {
    std::unique_ptr<Animal> a[] = {std::make_unique<Dog>(), std::make_unique<Cat>()};
    for (const auto& x : a) x->sound();
}
Output

Woof
Meow

See Polymorphism and Virtual Functions.

What is a pure virtual function and an abstract class in C++?

virtual void f() const = 0; is a pure virtual function. A class with at least one is an abstract class: you can not create an object of it, and the derived classes must implement the function.

struct Shape {
    virtual double area() const = 0;
};

int main() {
    Shape s;
}
Output

Abstract.cpp: In function 'int main()':
Abstract.cpp:6:11: error: cannot declare variable 's' to be of abstract type 'Shape'
6 | Shape s;
| ^
Abstract.cpp:1:8: note: because the following virtual functions are pure within 'Shape':
1 | struct Shape {
| ^~~~~
• 'virtual double Shape::area() const'
Abstract.cpp:2:20:
2 | virtual double area() const = 0;
| ^~~~

See Abstract Classes and Interfaces.

What is the difference between new and malloc in C++?

Pointnew / deletemalloc / free
LanguageC++C (also usable in C++)
ConstructorCalledNot called
Return typeThe correct pointer typevoid* (needs a cast)
On failureThrows std::bad_allocReturns NULL
SizeCalculated by the compilerYou give the bytes
#include <iostream>

struct Item {
    Item() { std::cout << "constructed\n"; }
    ~Item() { std::cout << "destroyed\n"; }
};

int main() {
    Item* p = new Item;       // allocates and constructs
    delete p;                 // destroys and frees
}
Output

constructed
destroyed

In modern C++ do not write them by hand. Use std::make_unique and containers. See Dynamic Memory and Smart Pointers.

What is a memory leak in C++ and how to avoid it?

A memory leak happens when you allocate memory with new and lose the pointer without delete. The program uses more and more memory.

#include <iostream>
#include <memory>

int main() {
    int* leak = new int(5);
    leak = nullptr;                       // the address is lost: a leak (the memory is never freed)

    auto safe = std::make_unique<int>(5); // freed automatically
    std::cout << *safe << '\n';
}
Output

5

How to avoid it: use std::unique_ptr and std::shared_ptr, use containers (vector, string) and follow RAII. Tools like AddressSanitizer (-fsanitize=address) and Valgrind find leaks. See Smart Pointers.

What is nullptr in C++? What is the difference from NULL?

nullptr means “points to nothing”. It has the type std::nullptr_t. The old NULL is just the number 0, which can confuse overloaded functions.

#include <iostream>

void f(int)   { std::cout << "int\n"; }
void f(char*) { std::cout << "pointer\n"; }

int main() {
    f(0);              // int
    f(nullptr);        // pointer
    int* p = nullptr;
    std::cout << (p == nullptr) << '\n';
}
Output

int
pointer
1

Always initialize pointers with a value or nullptr. See Pointers.

What is the difference between an array and a vector in C++?

PointC arraystd::arraystd::vector
SizeFixedFixedChanges at run time
Knows its sizeNoYesYes
MemoryStackStackHeap
Bounds check with at()NoYesYes
Add itemsNoNopush_back
#include <array>
#include <iostream>
#include <vector>

int main() {
    int c[3] = {1, 2, 3};
    std::array<int, 3> a = {1, 2, 3};
    std::vector<int> v = {1, 2, 3};
    v.push_back(4);
    std::cout << sizeof(c) / sizeof(c[0]) << ' ' << a.size() << ' ' << v.size() << '\n';
}
Output

3 3 4

See Arrays and Vectors.