Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Type Conversion C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers C++ Memory Mgmt

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion C++ Lambda

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Destructors C++ The this Pointer C++ Access Specifiers C++ Encapsulation C++ Friend Functions C++ Inheritance C++ Polymorphism C++ Operator Overload C++ Templates

C++ Files

C++ Files

C++ Date

C++ Date

C++ Errors

C++ Errors C++ Debugging C++ Exceptions C++ Input Validation

C++ Problem Solving

C++ Problem Solving C++ Build the Logic C++ Test Cases

C++ Projects

C++ Projects

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Unordered Map C++ Unordered Set C++ Iterators C++ Algorithms

C++ Namespaces

C++ Namespaces

C++ Cert

C++ Certificate

C++ How To

C++ How Tos

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Code Challenges C++ Practice Problems C++ Syllabus C++ Study Plan C++ Interview Q&A

C++ Reference

C++ Reference C++ Keywords C++ <algorithm> C++ <cctype> C++ <cmath> C++ <cstdlib> C++ <cstring> C++ <ctime> C++ <deque> C++ <fstream> C++ <iomanip> C++ <iostream> C++ <list> C++ <map> C++ <memory> C++ <queue> C++ <random> C++ <set> C++ <sstream> C++ <stack> C++ <stdexcept> C++ <string> C++ <unordered_map> C++ <unordered_set> C++ <vector>


C++ Interview Questions


Share

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 cout and string, belong to the std namespace.
  • using namespace std; lets you write cout instead of std::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:

  • cout prints output to the screen, with the << operator.
  • cin reads 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 an int to the operating system when the program ends.
  • 0 means 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:

  • int for whole numbers, float and double for decimal numbers, char for single characters, and bool for true or false.
  • string stores 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:

  • auto lets 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 auto must 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. ++i adds 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:

  • const creates a variable that cannot be changed. It has a type, so the compiler can check it.
  • #define is a text replacement that happens before the code is compiled. It has no type. In C++, const is 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:

  • break stops the loop completely.
  • continue skips 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 next case too. 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 string is a class from the <string> library. It can grow, and it has useful functions like length() and append().
  • A C-style string is a char array 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 as vector:
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:

  • sizeof gives 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 vector can grow and shrink. Use push_back() to add an element, and size() 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 the int version.

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 class and a struct can both have attributes and methods.
  • The difference is the default access: members of a class are private by default, and members of a struct are public by 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 - like private, 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:

  • this is 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:

  • new and delete are C++ operators. new gets memory and calls the constructor, and delete calls the destructor before the memory is freed.
  • malloc() and free() come from C. They only get and free memory, and they do not call constructors or destructors.
  • Use delete[] for memory that was created with new[]:
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 new is never freed with delete.
  • 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_ptr is the only owner of the memory. shared_ptr can 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 map keeps its keys sorted.
  • An unordered_map does 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 try block. Use throw to report an error, and catch to 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



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.