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:
$ 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,
newanddelete, 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++?
| Point | C | C++ |
|---|---|---|
| Style | Procedural | Procedural, object oriented, generic |
| Classes | No | Yes |
| Overloading | No | Yes |
| References | No | Yes |
| Templates, exceptions | No | Yes |
| Strings and containers | char arrays, own code | std::string, STL |
| Memory | malloc and free | new, delete, smart pointers |
| I/O | printf, scanf | cout, 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);
}
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++?
| Standard | Main additions |
|---|---|
| C++98 / 03 | Templates, STL, exceptions, namespaces |
| C++11 | auto, lambdas, nullptr, move semantics, smart pointers, range for |
| C++14 | Generic lambdas, make_unique |
| C++17 | Structured bindings, optional, variant, string_view, filesystem |
| C++20 | Concepts, ranges, modules, coroutines, std::format |
| C++23 | std::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
}
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++?
| Point | std::cout | printf | std::print (C++23) |
|---|---|---|---|
| Language | C++ | C | C++23 |
| Type safe | Yes | No | Yes |
| Format | Stream operators << | %d, %s codes | {} placeholders |
| Custom types | With operator<< | No | With 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);
}
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
}
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';
}
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++?
| Point | Reference | Pointer |
|---|---|---|
| Must be initialized | Yes | No |
| Can be null | No | Yes |
| Can be changed to refer to another variable | No | Yes |
| Use | Like a normal variable | Needs * and -> |
| Size | Same 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';
}
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';
}
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;
}
parameterized
default
parameterized
copy
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";
}
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"));
}
int 5
double 2.5
string hello
What is the difference between overloading and overriding in C++?
| Point | Overloading | Overriding |
|---|---|---|
| Where | Same scope | Base and derived class |
| Parameters | Different | Same |
| Needs virtual | No | Yes (for run time behavior) |
| Decided | Compile time | Run 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);
}
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();
}
Woof
Meow
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;
}
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;
| ^~~~
What is the difference between new and malloc in C++?
| Point | new / delete | malloc / free |
|---|---|---|
| Language | C++ | C (also usable in C++) |
| Constructor | Called | Not called |
| Return type | The correct pointer type | void* (needs a cast) |
| On failure | Throws std::bad_alloc | Returns NULL |
| Size | Calculated by the compiler | You 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
}
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';
}
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';
}
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++?
| Point | C array | std::array | std::vector |
|---|---|---|---|
| Size | Fixed | Fixed | Changes at run time |
| Knows its size | No | Yes | Yes |
| Memory | Stack | Stack | Heap |
| Bounds check with at() | No | Yes | Yes |
| Add items | No | No | push_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';
}
3 3 4