C++ Interview Questions
C++ Interview Questions with Answers
This page has common C++ interview questions, with short answers and code examples. The questions go from the basics to classes, pointers and memory management, which almost every C++ interview includes.
Each answer links to the tutorial chapter where you can learn more. At the end of the page, you can test yourself with an interview quiz.
- C++ basics
- Data types and operators
- Conditions and loops
- Strings and arrays
- References and pointers
- Functions
- Classes and objects
- Memory management
- STL and more
C++ Basics
1. What is the difference between C and C++?
Answer:
- C++ was made as an extension of C, and both languages have almost the same syntax.
- The main difference is that C++ supports classes and objects, while C does not. C++ also has references, function overloading, templates and the Standard Template Library (STL).
Learn more: C++ Introduction
2. What does using namespace std; do?
Answer:
- Names from the standard library, like
coutandstring, belong to thestdnamespace. using namespace std;lets you writecoutinstead ofstd::cout:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!"; // The same as std::cout
return 0;
}
Learn more: C++ Namespaces
3. What is the difference between cout and cin?
Answer:
coutprints output to the screen, with the<<operator.cinreads input from the keyboard, with the>>operator:
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age;
Learn more: C++ User Input
4. What does main() return, and why?
Answer:
main()returns anintto the operating system when the program ends.0means that the program finished with no errors. Any other value means that something went wrong.
Learn more: C++ Syntax
Data Types and Operators
5. What are the basic data types in C++?
Answer:
intfor whole numbers,floatanddoublefor decimal numbers,charfor single characters, andboolfortrueorfalse.stringstores text. It is not a basic type, but a class from the<string>library.
Learn more: C++ Data Types
6. What does the auto keyword do?
Answer:
autolets the compiler find the type of a variable from the value that you give it:
auto x = 5; // int
auto price = 9.99; // double
auto letter = 'A'; // char
- A variable with
automust get a value when you create it.
Learn more: C++ The auto Keyword
7. What is the difference between i++ and ++i?
Answer:
- Both add 1 to
i. i++uses the current value first, and then adds 1.++iadds 1 first, and then uses the new value:
int i = 5;
int a = i++; // a is 5, i is 6
int j = 5;
int b = ++j; // b is 6, j is 6
Learn more: C++ Arithmetic Operators
8. What does 7 / 2 give in C++?
Answer:
- When both numbers are integers, the result is also an integer, and the decimals are removed.
- If one of the numbers is a
double, the result keeps the decimals:
cout << 7 / 2; // 3
cout << 7 / 2.0; // 3.5
Learn more: C++ Type Conversion
9. What is the difference between const and #define?
Answer:
constcreates a variable that cannot be changed. It has a type, so the compiler can check it.#defineis a text replacement that happens before the code is compiled. It has no type. In C++,constis usually the better choice:
const int maxUsers = 100; // Has a type (int)
#define MAX_USERS 100 // Text replacement, no type
Learn more: C++ Constants
Conditions and Loops
10. What is the difference between break and continue?
Answer:
breakstops the loop completely.continueskips the rest of the current round, and goes on with the next one:
for (int i = 1; i <= 5; i++) {
if (i == 2) {
continue; // Skip 2
}
if (i == 4) {
break; // Stop at 4
}
cout << i << "\n";
}
// Prints 1 and 3
Learn more: C++ Break and Continue
11. What happens if you forget break in a switch?
Answer:
- Without
break, the program goes on and runs the code in the nextcasetoo. This is called fall-through:
int day = 1;
switch (day) {
case 1:
cout << "Monday\n";
case 2:
cout << "Tuesday\n";
break;
}
// Prints Monday and Tuesday
Learn more: C++ Switch
12. What is a range-based for loop?
Answer:
- A range-based for loop (also called a for-each loop) goes through all the elements in an array or a container, like a
vector. - You do not need a counter or an index:
int numbers[3] = {10, 20, 30};
for (int n : numbers) {
cout << n << "\n";
}
Learn more: C++ The foreach Loop
Strings and Arrays
13. What is the difference between string and a C-style string?
Answer:
- A
stringis a class from the<string>library. It can grow, and it has useful functions likelength()andappend(). - A C-style string is a
chararray that ends with a null character (\0). It is used in C, and in older C++ code:
string greeting1 = "Hello"; // string
char greeting2[] = "Hello"; // C-style string
Learn more: C++ C-Style Strings
14. What is the difference between length() and size() for a string?
Answer:
- There is no difference. Both return the number of characters in a
string. size()exists so that strings work like the other containers, such asvector:
string name = "Liam";
cout << name.length(); // 4
cout << name.size(); // 4
Learn more: C++ String Length
15. How do you find the number of elements in an array?
Answer:
sizeofgives the size of the whole array in bytes. Divide it by the size of one element:
int numbers[5] = {10, 20, 30, 40, 50};
int count = sizeof(numbers) / sizeof(numbers[0]); // 5
Learn more: C++ Get Array Size
16. What is the difference between an array and a vector?
Answer:
- An array has a fixed size. You cannot add more elements after it is created.
- A
vectorcan grow and shrink. Usepush_back()to add an element, andsize()to get the number of elements:
vector<string> cars = {"Volvo", "BMW"};
cars.push_back("Ford");
cout << cars.size(); // 3
Learn more: C++ Vectors
References and Pointers
17. What is a reference?
Answer:
- A reference is another name for an existing variable. It is created with the
&operator. - When you change the reference, you change the original variable:
string food = "Pizza";
string &meal = food;
meal = "Burger";
cout << food; // Burger
Learn more: C++ References
18. What is the difference between a pointer and a reference?
Answer:
- A pointer stores a memory address. You can change it to point to another variable, and you use
*to get the value. - A reference is another name for a variable. It must get a value when it is created, and it cannot be changed to refer to another variable:
int x = 10;
int* ptr = &x; // Pointer: stores the address of x
int& ref = x; // Reference: another name for x
cout << *ptr; // 10
cout << ref; // 10
Learn more: C++ Pointers
19. What is the difference between pass by value and pass by reference?
Answer:
- With pass by value, the function gets a copy. Changes inside the function do not change the original variable.
- With pass by reference (
&), the function works on the original variable:
void addOne(int n) { // Pass by value
n++;
}
void addOneRef(int &n) { // Pass by reference
n++;
}
int x = 5;
addOne(x); // x is still 5
addOneRef(x); // x is now 6
Learn more: C++ Pass By Reference
Functions
20. What is function overloading?
Answer:
- Function overloading means that several functions can have the same name, as long as their parameters are different:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
- The compiler chooses the right function from the arguments, so
add(2, 3)calls theintversion.
Learn more: C++ Function Overloading
21. What is a default parameter?
Answer:
- A default parameter has a value that is used when you call the function without that argument:
void greet(string name = "friend") {
cout << "Hello " << name << "\n";
}
greet("Liam"); // Hello Liam
greet(); // Hello friend
Learn more: C++ Default Parameters
22. What is recursion?
Answer:
- Recursion is when a function calls itself. It needs a condition that stops it, or it runs forever:
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
}
return 0;
}
cout << sum(5); // 15
Learn more: C++ Recursion
23. What is a lambda function?
Answer:
- A lambda is a small function without a name, that you can write directly in your code. It is often passed to other functions:
auto add = [](int a, int b) {
return a + b;
};
cout << add(3, 4); // 7
Learn more: C++ Lambda
Classes and Objects
24. What is the difference between a class and a struct?
Answer:
- In C++, a
classand astructcan both have attributes and methods. - The difference is the default access: members of a
classareprivateby default, and members of astructarepublicby default.
Learn more: C++ Structures
25. What are access specifiers?
Answer:
public- members can be used from outside the class.private- members can only be used inside the class.protected- likeprivate, but members can also be used in classes that inherit from it.
Learn more: C++ Access Specifiers
26. What is a constructor?
Answer:
- A constructor is a special method that runs automatically when you create an object.
- It has the same name as the class, and no return type:
class Car {
public:
string brand;
Car(string b) {
brand = b;
}
};
Car myCar("Volvo");
Learn more: C++ Constructors
27. What is a destructor?
Answer:
- A destructor runs automatically when an object is destroyed, for example when it goes out of scope.
- It has the name of the class with a
~in front, and it is often used to free memory or close files:
class Car {
public:
~Car() {
cout << "The car is destroyed\n";
}
};
Learn more: C++ Destructors
28. What is the this pointer?
Answer:
thisis a pointer to the current object.- It is often used when a parameter has the same name as an attribute:
class Car {
public:
string brand;
Car(string brand) {
this->brand = brand;
}
};
Learn more: C++ The this Pointer
29. What is inheritance?
Answer:
- Inheritance lets a class (the child) reuse the attributes and methods of another class (the parent).
- C++ also supports multiple inheritance, where a class inherits from more than one class:
class Vehicle {
public:
string brand = "Ford";
};
class Car : public Vehicle {
public:
string model = "Mustang";
};
Learn more: C++ Inheritance
30. What is a virtual function?
Answer:
- A virtual function can be overridden in a child class. When you call it with a pointer or a reference to the parent class, the version from the child class runs.
- Without
virtual, the version from the parent class runs:
class Animal {
public:
virtual void sound() {
cout << "Animal sound\n";
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Woof\n";
}
};
Dog myDog;
Animal* a = &myDog;
a->sound(); // Woof
Learn more: C++ Virtual Functions
31. What is an abstract class?
Answer:
- An abstract class has at least one pure virtual function, written with
= 0. - You cannot create objects of an abstract class. A child class must override the pure virtual function:
class Shape {
public:
virtual double area() = 0; // Pure virtual function
};
Learn more: C++ Abstract Classes
32. What is operator overloading?
Answer:
- Operator overloading lets you decide what an operator, like
+or==, does with objects of your own classes:
class Point {
public:
int x, y;
Point(int a, int b) {
x = a;
y = b;
}
Point operator+(const Point& other) {
return Point(x + other.x, y + other.y);
}
};
Learn more: C++ Operator Overloading
Memory Management
33. What is the difference between new/delete and malloc()/free()?
Answer:
newanddeleteare C++ operators.newgets memory and calls the constructor, anddeletecalls the destructor before the memory is freed.malloc()andfree()come from C. They only get and free memory, and they do not call constructors or destructors.- Use
delete[]for memory that was created withnew[]:
int* number = new int(5);
int* numbers = new int[10];
delete number;
delete[] numbers;
Learn more: C++ new and delete
34. What is a memory leak?
Answer:
- A memory leak happens when memory that was created with
newis never freed withdelete. - The program keeps the memory until it ends. If it happens many times, for example in a loop, the program uses more and more memory.
Learn more: C++ Memory Management
35. What are smart pointers?
Answer:
- Smart pointers free the memory automatically, so you do not need to call
delete. They are in the<memory>library. unique_ptris the only owner of the memory.shared_ptrcan have many owners, and the memory is freed when the last one is gone:
unique_ptr<int> p(new int(25));
cout << *p; // 25
// The memory is freed automatically
Learn more: C++ Smart Pointers
STL and More
36. What is the difference between map and unordered_map?
Answer:
- A
mapkeeps its keys sorted. - An
unordered_mapdoes not sort the keys, but it is usually faster to find, add and remove elements.
Learn more: C++ Maps and C++ Unordered Map
37. What is a template?
Answer:
- A template lets you write one function or class that works with many data types:
template <typename T>
T bigger(T a, T b) {
return (a > b) ? a : b;
}
cout << bigger(3, 7); // 7
cout << bigger(2.5, 1.5); // 2.5
Learn more: C++ Templates
38. How do you handle errors with exceptions?
Answer:
- Put the code that can fail in a
tryblock. Usethrowto report an error, andcatchto handle it:
try {
int age = 15;
if (age < 18) {
throw age;
}
cout << "Access granted";
} catch (int myNum) {
cout << "Access denied. Age is: " << myNum;
}
Learn more: C++ Exceptions
Test Yourself: Interview Quiz
Ready for the interview? Choose your answer to each question, and read the explanation:
Question
Code
Explanation
Prepare for Your Interview
- Test yourself with our C++ Exercises and C++ Quiz
- Solve C++ Practice Problems, and see how many test cases your code passes
- Show what you know with the C++ Certificate